Slim框架引入Eloquent ORM

一、添加Slim的数据库配置:

$config = [
        'settings' => [
                'determineRouteBeforeAppMiddleware'=>false,
                'displayErrorDetails'=>true,
                'db'=>[
                        'driver'=>'mysql',
                        'host'=>'localhost',
                        'database'=>'wechat',
                        'username'=>'root',
                        'password'=>'zxj1105511101',
                        'charset'=>'utf8',
                        'collation'=>'utf8_unicode_ci',
                        'prefix'=>'',
                ]
        ]
];

$app = new \Slim\App($config);

二、添加ORM的Service factory(配置Eloquent):

$container = $app->getContainer();
$container['db'] = function($container){
        $capsule = new \Illuminate\Database\Capsule\Manager;
        $capsule->addConnection($container['settings']['db']);
        $capsule->setAsGlobal();
        $capsule->bootEloquent();
        return $capsule;
};

三、传递table object到controller中:

$container[\App\WidgetController::class] = function($c){
        $table = $c->get('db')->table('users');
        return new \App\WidgetController($table);
};

四、从controller中查询数据库的表:

table = $table;
    }

    public function __invoke(Request $request, Response $response, $args)
    {   
        return $response;
    }

    public function getUser(Request $request, Response $response, $args)
    {
        $records = $this->table->where('username','like','%test%')->get();
        foreach($records as $value){
                print_r($value->username)."
"; } } }

五、以controller的methods作为路由的回调函数:

$app->get('/test',App\WidgetController::class.':getUser');


你可能感兴趣的:(Slim)