PHP Slim 3 Framework - Use MonoLog in Custom Class - Using $this when not in object context

喜欢而已 提交于 2019-12-11 16:38:28

问题


Im am working from the Slim 3 skeleton and trying to use the MonoLog in a custom class I have created which is called Utilities.

Utilities.php - which is required from index.php

<?php

class Utilities {

    protected $logger;

    function __construct($c) {
        $this->logger = $logger;
    }

    static function checkPerms() {
        $this->logger->info("checkPerms() permissions of user id valid.");
        return true;
    }

}

Dependencies.php - I added the following:

$container['utilities'] = function ($c) {
    return new Utilities($c->get('logger'));   
};

But I am getting the error of:

Message: Using $this when not in object context

File: /Applications/MAMP/htdocs/project/src/utilities.php

I must be missing something but I am not sure what?


回答1:


I would refactor Utilities.php a little bit:

<?php

class Utilities
{

    protected $logger;

    function __construct($logger)
    {
        $this->logger = $logger;
    }

    public function checkPerms()
    {
        $this->logger->info("checkPerms() permissions of user id valid.");

        return true;
    }

}



回答2:


There are at least two important things that I would suggest.

The first is that a static method cannot call $this. In the Slim Skeleton, you see that the logger is called via the magic method __invoke. It does not have to be a magic method but just not a "static function" in order to access $this.

The second is the constructor. Even though in your dependencies you specified that you want to retrieve the logger from the container, your current constructor does not refer to it. You see that again in the Slim skeleton boilerplate. If you don't want to use the "use" declarations, you could do:

function __construct(\Psr\Log\LoggerInterface $logger) {
    $this->logger = $logger;
}

This way, the container will get you the $logger you need and then you can use non-static methods to call it.

<?php
namespace App\Action;

use Slim\Views\Twig;
use Psr\Log\LoggerInterface;
use Slim\Http\Request;
use Slim\Http\Response;

final class HomeAction
{
    private $view;
    private $logger;

    public function __construct(Twig $view, LoggerInterface $logger)
    {
        $this->view = $view;
        $this->logger = $logger;
    }

    public function __invoke(Request $request, Response $response, $args)
    {
        $this->logger->info("Home page action dispatched");

        $this->view->render($response, 'home.twig');
        return $response;
    }
}

Good luck to you



来源:https://stackoverflow.com/questions/52843148/php-slim-3-framework-use-monolog-in-custom-class-using-this-when-not-in-obj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!