用户
 找回密码
 入住 CI 中国社区
搜索
查看: 11683|回复: 13
收起左侧

[版本 4.x] 欢迎交流CI4实际开发中的问题,本人正在开发的小项目

[复制链接]
发表于 2020-8-3 21:43:24 | 显示全部楼层 |阅读模式
一直在使用ci 框架,做为学化工出生,用这框架真是得心应手.从ci3 到 ci4 , 质的飞跃, 命名空间的使用 太好用了 ,还在继续挖掘和学习中
感觉好多功能都还没用到, 目前最多的还是 最常用的 curd 操作 ,比较我还是棵 菜菜

现在忙着做个小型分销商城,支持模块氏开发,截图展示一下,(欢迎各位留帖交流心得)

微信截图_20200803213920.png

微信截图_20200803214217.png



发表于 2020-8-4 22:13:03 | 显示全部楼层
如果将模块放在app目录下面,helper函数不能同时加载应用helper文件与模块helper文件。
官方的示例是将模块放在ROOTPATH下面(与app目录同级)
回复 支持 1 反对 0

使用道具 举报

发表于 2021-9-10 15:47:12 | 显示全部楼层
本帖最后由 yoyoyuye 于 2021-9-10 15:53 编辑

基于CI4 自带的restFull。
SQL复制代码
 
/*
Navicat MySQL Data Transfer
 
Source Server         : localhost
Source Server Version : 50726
Source Host           : localhost:3306
Source Database       : ci4
 
Target Server Type    : MYSQL
Target Server Version : 50726
File Encoding         : 65001
 
Date: 2021-09-10 15:43:02
*/

 
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for `my_news`
-- ----------------------------
DROP TABLE IF EXISTS `my_news`;
CREATE TABLE `my_news` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `auth` VARCHAR(20) NOT NULL,
  `img_path` VARCHAR(100) NOT NULL,
  `title` VARCHAR(128) NOT NULL,
  `slug` VARCHAR(128) NOT NULL,
  `body` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `slug` (`slug`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of my_news
-- ----------------------------
INSERT INTO `my_news` VALUES ('1', 'admin', './public/uploads/images/logo.png', '测试数据一条11112222', '什么意思呢', '何必你好1212');
INSERT INTO `my_news` VALUES ('11', '', '', '再加一个', '加一个什么呢', '看不看得到啊');
INSERT INTO `my_news` VALUES ('12', '', '', '随便写', '写一个什么呢啊啊a', 'a阿萨v阿萨阿斯顿啊啊啊啊阿萨');
INSERT INTO `my_news` VALUES ('3', '', '', 'Caffeination, Yes!', 'caffeination-yes', 'World\'s largest coffee shop␣\r\n都是啥玩意');
INSERT INTO `my_news` VALUES ('5', '', '', '呵呵呵呵', '士大夫打撒', '士大夫大师傅撒飞洒发生发生发生飞洒发生');
INSERT INTO `my_news` VALUES ('6', '', '', '温德尔瓦', '巍峨哇', '温热嗡嗡嗡我认为');
INSERT INTO `my_news` VALUES ('7', '', '', '取桥桥', '的撒范德萨', '是否是否打算打发发书法大赛v士大夫打撒');
INSERT INTO `my_news` VALUES ('8', '', '', '胜多负少', '士大夫打撒是', '士大夫打撒');
INSERT INTO `my_news` VALUES ('9', '', '', '331我顶顶顶顶是', '首发式发生', '上的发大水发大水发大水发生发生发啊沙发沙发阿斯顿发顺丰');
 
 
复制代码

model:

PHP复制代码
 
<?php
namespace App\Models\Apimodel;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class News_model extends \CodeIgniter\Model{
    protected  $table='my_news';
    protected $primarykey='id';
    protected  $allowedFields=[
        'auth',
        'title',
        'img_path',
        'slug',
        'body',
    ];
}
 
 
 
复制代码

控制器:
PHP复制代码
 
<?php
namespace App\Controllers\Api;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

class News extends ResourceController{
    use ResponseTrait;
    public function index(){
        $model=New \App\Models\Apimodel\News_model();
        $data=$model->findAll();
        return $this->respond($data);
    }
    public function show($id=null){
        $model=new \App\Models\Apimodel\News_model();
        $data=$model->getwhere(['id'=>$id])->getResult();
        if($data){
            return $this->respond($data);
        }else{
            return $this->failNotFound("没有找到这个id=".$id."的数据.");
        }
    }
    public function add(){
        $model=new \App\Models\Apimodel\News_model();
        $data['auth']=$this->request->getVar('auth');
        $data['img_path']=$this->request->getVar('img_path');
        $data['title']=$this->request->getVar('title');
        $data['slug']=$this->request->getVar('slug');
        $data['body']=$this->request->getVar('body');
        $model->insert($data);
        $response=[
            'status'=>201,
            'error'=>null,
            'message'=>[
                'success'=>'数据添加成功',
            ]
        ];
        return $this->respondCreated($response);
    }
    public function update($id=null){
        $model=New \App\Models\Apimodel\News_model();
        $input=$this->request->getRawInput();
        $data=[
            'auth'=>$input['auth'],
            'img_path'=>$input['img_path'],
            'title'=>$input['title'],
            'slug'=>$input['slug'],
            'body'=>$input['body'],
        ];
        $model->update($id,$data);
        $response=[
            'status'=>200,
            'error'=>null,
            'message'=>[
                'success'=>'数据更新成功',
            ],
        ];
        return $this->respond($response);
    }
    public function del($id=null){
        $model=new \App\Models\Apimodel\News_model();
        $data=$model->find($id);
        if($data){
            $model->delete($id);
            $response=[
                'status'=>200,
                'error'=>null,
                'message'=>[
                    'success'=>'数据删除成功',
                ]
            ];
            return $this->respondDeleted($response);
        }else{
            return $this->failNotFound("没有找到这个id=".$id."的数据.");
        }
    }
}
 
复制代码



 楼主| 发表于 2020-8-5 09:16:41 | 显示全部楼层
xgdd1987 发表于 2020-8-5 09:07
兄弟,ApiBase.php能分享下吗?我参考参考你是怎么实现的。

我是菜鸟啊 小老弟,
不是restfull形式,是普通的 路由访问

PHP复制代码
 
 
<?php
namespace App\Controllers;
 
/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

 
use App\Controllers\BaseController;
use App\Models\ApisModel;
 
class ApiBase extends BaseController
{
 
    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */

    protected $helpers = [];
    protected $apisModel;
    protected $mokappkey;
    protected $mokappsecret;
    protected $moktoken;//接口令牌 有效期1周 过期后 重新换取
    protected $mokapp; //当前接口应用信息
    protected $usertoken;//用户令牌
    protected $user;
 
    /**
     * Constructor.
     */

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);
 
        $this->apisModel = new ApisModel();
 
        $this->usertoken = $this->request->getHeaderLine('token');
        $this->moktoken = $this->request->getHeaderLine('moktoken');
        $this->mokappkey = $this->request->getHeaderLine('mokappkey');
        $this->mokappsecret = $this->request->getHeaderLine('mokappsecret');
 
 
            $this->checkApiToken();//
 
        $this->getUserInfor();
 
    }
 
    //通过mokappkey 和 mokappsecret 生成 token 一周有效期
    protected function createApiToken()
    {
        $data = $this->apisModel->getOpenByKey($this->mokappkey);
        if (!$data) {
            $this->_json(1, '应用不存在');
        }
        $this->mokapp = $data;
        $secret = md5($data['secret'] . $data['key']);
        if ($secret != $this->mokappsecret) {
            $this->_json(1, '应用授权错误');
        }
        $this->moktoken = md5($secret);
        //生成apptoken
        $this->cache->save($this->moktoken, ['id' => $data['id'], 'key' => $data['key'], 'userid' => $data['userid'], 'platform' => $data['platform']], WEEK);
        $this->_json(0, 'ok', $this->moktoken);
    }
 
    protected function checkApiToken()
    {
        $value = $this->cache->get($this->moktoken);
        return $value;
    }
 
    public function getUserInfor()
    {
        $cache = $this->cache->get($this->usertoken);
        if (!$cache) {
            $this->userid = 0;
            $this->user = null;
            return '';
        }
        if (isset($cache['userid']) && $cache['userid']) {
            $this->userid = $cache['userid'];
            $this->session->set('userid', $this->userid);
            $this->user = $this->userModel->getUser($this->userid);
            $this->renderer->setData(['user' => $this->user, 'userid' => $this->userid]);
        }
 
    }
 
}
 
 
 
 
复制代码

 楼主| 发表于 2020-8-4 22:18:12 | 显示全部楼层
blackice 发表于 2020-8-4 22:13
如果将模块放在app目录下面,helper函数不能同时加载应用helper文件与模块helper文件。
官方的示例是将模块 ...

我的多模块 里面只有控制器,模型,类文件...带命名空间的就可以用
比如
Apps/School/Controller/Home.php
Apps/School/...

Apps/News/Controller/Home.php
Apps/News/.....
helper 统一放在主项目,可以用不同的文件区分就行
发表于 2020-8-5 09:07:09 | 显示全部楼层
兄弟,ApiBase.php能分享下吗?我参考参考你是怎么实现的。
 楼主| 发表于 2020-8-5 09:24:13 | 显示全部楼层
xgdd1987 发表于 2020-8-5 09:07
兄弟,ApiBase.php能分享下吗?我参考参考你是怎么实现的。

你用的是 RESTFUL 风格 还是什么样的
我看手册里有 RESTFUL 相关的资料,打算下一波优化的时候,再考虑 RESTFUL形式接入
发表于 2020-8-5 11:12:11 | 显示全部楼层
连普科技 发表于 2020-8-5 09:24
你用的是 RESTFUL 风格 还是什么样的
我看手册里有 RESTFUL 相关的资料,打算下一波优化的时候,再考虑 RES ...

我在考虑用RESTFUL的方式去写,CI4第一次用,还不熟悉。多谢啦。等我写出来,我会分享下。
发表于 2020-9-18 08:52:47 | 显示全部楼层
在开发中涉及到 CI4 动态加载语言包的问题了吗? 比如加载 中文包 还是英文包。 我看手册只有本地化检验,没介绍怎么样手工加载。
发表于 2020-9-18 09:42:34 | 显示全部楼层
已解决

        $language = service('language');
        $language->setLocale('cn');
 楼主| 发表于 2020-9-18 10:43:18 | 显示全部楼层
binhaiit 发表于 2020-9-18 09:42
已解决

        $language = service('language');

标记一下 以后估计会用到 谢谢

本版积分规则