Search code examples
phplaravelphpmd

PHPMD complains about static usage of "Log"


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!


Solution

  • 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.