draj840143 2018-12-14 18:12 采纳率: 100%
浏览 71

Slim 3 Controller问题:当不在对象上下文中时使用$ this

Having an issue using $this->container inside of my controllers.

When I try to access the logger/monolog in the code below, it fails miserably:

$this->container->get('logger')->addInfo('Request: users->get-one');

Here's the code in src/dependancies.php:

<?php

$container = $app->getContainer();

// monolog
$container['logger'] = function ($c) {
    $logs = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($logs['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($logs['path'], $logs['level']));

    return $logger;
};

// database
$container['db'] = function ($c) {
    $database = $c->get('settings')['database'];

    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection([
        'driver' => 'mysql',
        'host' => $database['hostname'],
        'database' => $database['database'],
        'username' => $database['username'],
        'password' => $database['password'],
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();

    return $capsule;
};

// register users controller
require __DIR__ . '/../src/controllers/users.php';

$container['UsersController'] = function($c) {
    return new UsersController($c);
};

Below is the code that's in src/controllers/users.php:

<?php

use Psr\Container\ContainerInterface;
use Slim\Http\Request;
use Slim\Http\Response;

class UsersController {
    protected $container;

    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function get(Request $request, Response $response, $args) {
        $this->container->get('logger')->addInfo('Request: users->get-one');

        /**
         * TODO: Replace $args['id'] with the id from the current token payload
         */
        $data = Users::find($args['id']);

        return $response->withJSON($data)->withStatus(200);
    }

    public function create(Request $request, Response $response, $args) {
        $this->logger->addInfo('Request: users->create');

        $user = $request->getParsedBody();

        $data = Users::create([
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'email' => $user['email'],
            'password' => password_hash($user['password'], PASSWORD_BCRYPT),
            'telephone' => $user['telephone'],
            'timezone' => $user['timezone'],
            'verification' => '011010'
        ]);

        return $response->withJSON($data)->withStatus(200);
    }

    public function update(Request $request, Response $response, $args) {
        $this->logger->addInfo('Request: users->update');

        $user = $request->getParsedBody();

        $data = Users::where('id', $args['id'])->update([
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'email' => $user['email'],
            'password' => password_hash($user['password'], PASSWORD_BCRYPT),
            'telephone' => $user['telephone'],
            'timezone' => $user['timezone']
        ]);

        return $response->withJSON($data)->withStatus(200);
    }

    public function delete(Request $request, Response $response, $args) {
        $this->logger->addInfo('Request: users->delete');

        $data = Users::destroy($args['id']);

        return $response->withJSON($data)->withStatus(200);
    }

    /*
    * ==============================
    * Manager Functions Routines
    * ==============================
    */
    public function getAll(Request $request, Response $response, $args) {
        $this->logger->addInfo('Request: admin->users->getAll');

        $data = Users::all();

        return $response->withJSON($data)->withStatus(200);
    }
}

I have tried following different tutorials as well as the documentation on the Slim website however, nothing has seemed to fix the issue. I am sure it's something easily fixed that I am just missing.

PHP Slim 3 Framework - Use MonoLog in Custom Class - Using $this when not in object context - The accepted answer here just seems silly to do when I want to be able to access the entire app container and NOT just the logger.

Any help is appreciated.

Thank you!

  • 写回答

1条回答 默认 最新

  • dtye7921 2018-12-14 18:44
    关注

    Well, I figured it out. Apparently using two semicolons when invoking the controller routine is not the proper way of doing things. Oops!

    /*
     * users::read::one
     * method:get
     */
    $app->get('/users', '\UsersController::get');
    

    When the code above is adjust to only use one semicolon, it works:

    /*
     * users::read::one
     * method:get
     */
    $app->get('/users', '\UsersController:get');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等