0

I added phpmd to my Laravel project.

Now I have a remark about static usage of "Log".

namespace App\Http\Controllers;

use Log;

class MyController extends Controller
{
/**
 * Does something
 */
public function doSomething($var)
{
Log::info('Just began to to something.');
}

phpmd says:

Avoid using static access to class '\Log' in method 'doSomething'.

What is the correct way to use Log class here?

I followed the Laravel docs but have no clue how to correct it and the phpmd docs do not help me due to my limited knowledge.

Thanks!

frankfurt-laravel
  • 3,731
  • 2
  • 20
  • 29
  • 1
    just use `info('text here...');` – Paladin Nov 29 '19 at 12:05
  • 1
    its a facade, it is literally a "static proxy" for another class, you are not directly calling a static method on the underlying class – lagbox Nov 29 '19 at 12:06
  • Some would say the correct way to do it would be to not use facade and use proper dependency injection, which is completely hidden by the facade. – Arcesilas Nov 29 '19 at 12:47
  • 2
    I don't agree on most things Mess detector complains about in regards to frameworks. I think it is more important to follow the frameworks best practices than mess detector :) – mrhn Nov 29 '19 at 13:00

1 Answers1

2

According to PHPMD documentation regarding static access

Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.

However Laravel facades could be considered a valid case for static class access, because they can be mocked.

Personally I prefer dependency injection over the use of static classes like Log. Doing so will result in the following code

namespace App\Http\Controllers;

use Log;
use Psr\Log\LoggerInterface;

class MyController extends Controller
{
    /**
     * @var LoggerInterface
     */
    private $logger;

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

    /**
     * Does something
     */
    public function doSomething($var)
    {
        $this->logger->info('Just began to to something.');
    }
}

So depending on preference the rule can either be disabled or you could use dependency injection over facades.

PtrTon
  • 3,705
  • 2
  • 14
  • 24