Elliot Reeve
Elliot Reeve

Reputation: 941

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

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?

Upvotes: 0

Views: 609

Answers (2)

odan
odan

Reputation: 4952

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

}

Upvotes: 1

farhang
farhang

Reputation: 407

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

Upvotes: 1

Related Questions