039.CI4框架CodeIgniter,封裝Model模型繫結資料庫的封裝

像一棵海草海草海草發表於2024-08-31

01、ModelBase.php程式碼如下:

<?php

namespace App\Models;

use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;

class ModelBase extends Model
{
    var $Db;

    function __construct(ConnectionInterface $db = null,
                         ValidationInterface $validation = null)
    {
        parent::__construct($db, $validation);
        //建立資料庫連線
        $this->Db = \Config\Database::connect();
    }

    //--------------------------------------------------------------------
    public function find($id = false)
    {
        if ($id === false) {
            return $this->findAll();
        }
        return $this->where(['id' => $id])->first();
    }

    public function date_insert($data)
    {
        return $this->insert($data);
    }

    public function date_update($data, $id)
    {
        return $this->update($id, $data);
    }

    public function date_delete($id)
    {
        return $this->delete($id);
    }

}

02、Model_usertoken.php程式碼如下:

<?php

namespace App\Models;

class Model_usertoken extends ModelBase
{
    protected $table = 'user_token';
    protected $primaryKey = 'id';
    protected $allowedFields = ['username', 'token', 'exp_time'];

    public function __construct()
    {
        parent::__construct();
    }

    public function date_query($date)
    {
        $id = $date['id'];
        //sql語句
        $sql = 'SELECT * FROM `user` WHERE `ID` IN ? ';
        //帶引數條件查詢
        $rst = $this->db->query($sql,
            [$id]
        );
        echo $this->db->getLastQuery();
        return $rst->getResultArray();
    }

}

03、呼叫如下:

<?php

namespace App\Controllers\Auth;

use App\Controllers\BaseController;

class Login extends baseController
{
    protected $userModelToken;


    function __construct()
    {
        $this->Jwt = new Tx_jwt;
        $this->userModelToken = model('App\Models\Model_usertoken');
    }

    //http://localhost/phmci4/public/index.php/auth/login/test001
    public function test001()
    {
        $param = array(
            'id' => [1],
        );
        $data = $this->userModelToken->date_query($param);
        ShowMessage($data);
    }

}

04、結構如下:

05、瀏覽器效果如下:

相關文章