COOLPHP基于Medoo在core\plugin\Model.php实现了初始化
/** * 模型父类 * @author 2daye */ namespace core\plugin; use Medoo\Medoo; class Model { /** * 数据库链接资源 * @var bool|Medoo * @author 2daye */ protected bool|Medoo $database = false; /** * 链接数据库 * @throws \Exception * @author 2daye */ public function __construct() { // 判断是否连接数据库 if ($this->database === false) { // 获取数据库配置 $dbConfig = Config::getAll('database'); $this->database = new Medoo([ 'type' => 'mysql', 'host' => $dbConfig['DB_HOST'], 'database' => $dbConfig['DB_NAME'], 'username' => $dbConfig['DB_USER'], 'password' => $dbConfig['DB_PASSWORD'], 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'port' => $dbConfig['DB_PORT_NUMBER'], // 表前缀 'prefix' => '', // 启用日志记录,默认情况下禁用它以获得更好的性能。 'logging' => true ]); } } }
之后统一继承父模型类,你也可以封装自己需要的数据库操作,例如:User模型的注册业务逻辑或基础的增删改查操作
namespace core\app\common\model; use core\plugin\Code; use core\plugin\Model; use core\plugin\RESTful; class User extends Model { // 表名 protected string $table = 'user'; /** * 注册 * @param array $data * @return array * @author 2daye */ public function register(array $data): array { $count = $this->database->count($this->table, ['phone' => $data['phone']]); // 如果用户存在就拒绝注册 if ($count > 0) { return (new RESTful())->response(Code::FORBIDDEN, '手机号已经存在')->array(); } $result = $this->database->insert($this->table, $data); // 判断用户是否新增成功 if ($result->rowCount() > 0) { return (new RESTful())->response(Code::OK)->array(); } return (new RESTful())->response(Code::INTERNAL_SERVER_ERROR)->array(); } }