【问题标题】:PHP Slim 3 Framework - Use MonoLog in Custom Class - Using $this when not in object contextPHP Slim 3 框架 - 在自定义类中使用 MonoLog - 不在对象上下文中使用 $this
【发布时间】:2018-10-16 19:56:20
【问题描述】:

我正在使用 Slim 3 骨架并尝试在我创建的名为 Utilities 的自定义类中使用 MonoLog。

Utilities.php - 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 - 我添加了以下内容:

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

但我收到以下错误:

消息:不在对象上下文中使用 $this

文件: /Applications/MAMP/htdocs/project/src/utilities.php

我一定错过了什么,但我不确定是什么?

【问题讨论】:

标签: php slim slim-3


【解决方案1】:

我会稍微重构一下 Utilities.php:

<?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】:

    我建议至少有两件重要的事情。

    首先是静态方法不能调用$this。在 Slim Skeleton 中,您会看到记录器是通过魔术方法 __invoke 调用的。为了访问 $this,它不必是一个神奇的方法,而不仅仅是一个“静态函数”。

    第二个是构造函数。即使在您的依赖项中您指定要从容器中检索记录器,您当前的构造函数也不会引用它。您在 Slim 骨架样板中再次看到了这一点。如果您不想使用“使用”声明,您可以这样做:

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

    这样,容器将为您提供所需的 $logger,然后您可以使用非静态方法来调用它。

    <?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;
        }
    }
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 2015-02-12
      • 1970-01-01
      • 2014-11-11
      • 2023-03-22
      相关资源
      最近更新 更多