0

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?

Community
  • 1
  • 1
Elliot Reeve
  • 901
  • 4
  • 21
  • 39
  • 2
    The problem is the static method checkPerms. It cannot access $this. Only non-static functions can. – farhang Oct 16 '18 at 20:22
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Nima Oct 16 '18 at 20:32

2 Answers2

1

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

farhang
  • 407
  • 1
  • 5
  • 13
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;
    }

}
odan
  • 4,757
  • 5
  • 20
  • 49