我正在使用 SLIM 4 开始一个 PET 项目,但我找不到在模型中使用与数据库的连接的方法。即使控制器工作正常。
我使用了一个容器来移动不同层之间的连接。
应用程序.php
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../../vendor/autoload.php';
//set container
$aux_container = new \DI\Container();
AppFactory::setContainer($aux_container);
$app = AppFactory::create();
//get container to manage dependencies on the rest of app files
$container = $app->getContainer();
require __DIR__ . '/../App/routes.php';
require __DIR__ . '/../App/configs.php';
require __DIR__ . '/../App/dependencies.php';
$app->run();
配置文件
<?php
$container->set('db_settings',function(){
return (object)[
"DB_NAME" => "prohip_operations",
"DB_USER" => "root",
"DB_PASS" => "root",
"DB_CHAR" => "utf8mb4",
"DB_HOST" => "localhost",
"DB_PORT" => "33066",
];
});
依赖项.php
<?php
use Psr\Container\ContainerInterface;
$container->set('db', function(ContainerInterface $c){
$config = $c->get('db_settings');
$host = $config->DB_HOST;
$pass = $config->DB_PASS;
$charset = $config->DB_CHAR;
$user = $config->DB_USER;
$dbname = $config->DB_NAME;
$port = $config->DB_PORT;
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
];
$dsn = "mysql:host=".$host.";port=".$port.";dbname=".$dbname.";charset=".$charset.";";
return new PDO($dsn, $user, $pass, $opt);
});
/Models/BaseModel.php
<?php
namespace App\Models;
use Psr\Container\ContainerInterface;
class BaseModel{
protected $container;
public function __construct(ContainerInterface $c){
$this->container = $c;
}
}
/Models/ApplicantStatus.php
<?php
namespace App\Models;
use App\Models\BaseModel;
class ApplicantStatus extends BaseModel{
public function __construct($id)
{
if(isset($id)){
$this->id = $id;
}
}
public function getStatusName(){
var_dump($this->container);
//get container db
$pdo = $this->container->get('db');
$query = $pdo->query('SELECT description_spanish FROM applicant_status WHERE id='.$this->id);
if($query->rowCount()>0){
return $query;
}
}
}
当使 $ this-> container 的 var_dump() 为 NULL 时,理论上他们威胁要从 BaseModel 初始化和扩展它...
此方法申请人状态-> getStatusName(); 它在控制器内部调用。
$status = new ApplicantStatus(11);
$status->getStatusName()
也许这就是我做错的地方......
谢谢