第一步:打開yaf命名空間
可以參考我的另外一篇文章:https://blog.csdn.net/zhezhebie/article/details/105920507
第二步:安裝medoo
composer require catfan/medoo
第三步:自動加載
public function _initLoad()
{
Yaf\Loader::import(APPLICATION_PATH . '/application/vendor/autoload.php');
}
第四步:連接數據庫
public function _initDatabase()
{
$arrConfig = Yaf\Registry::get('config');
$option = [
'database_type' => $arrConfig->database->database_type,
'database_name' => $arrConfig->database->database_name,
'server' => $arrConfig->database->server,
'username' => $arrConfig->database->username,
'password' => $arrConfig->database->password,
'prefix' => $arrConfig->database->prefix ?? '',
'charset' => $arrConfig->database->charset ?? 'utf8',
'logging' => $arrConfig->database->logging,
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
],
];
Yaf\Registry::set('db', new \Medoo\Medoo($option));
}
第五步:在模型裏面使用數據庫連接
<?php
/**
* @name SampleModel
* @desc sample數據獲取類, 可以訪問數據庫,文件,其它系統等
* @author admin
*/
class UserModel
{
private $db;
private $table = 'users';
public function __construct()
{
$this->db = Yaf\Registry::get('db');
}
function list() {
$users = $this->db->select($this->table, ['id', 'name']);
return $users;
}
}
最後效果圖: