Are Laravel facades dependencies?

拟墨画扇 提交于 2019-12-05 20:02:20
Decebal

Laravel facades are definitely dependencies, their intended use is for controllers, when building services and business logic you should try to make your dependencies as transparent as possible.

If you aim at achieving a SOLID implementation you will want to have all dependencies passed as params or in the class constructor.

Let's illustrate a little bit this abstractions:

before refactoring

Class PhotoService {

    protected $photosModel = null;

    public function getPhotos()
    { 
        $photos = Cache::get('photos');

        if (is_null($photos)) {
           return Photo::all();
        }
    }
}

still using facades, but solving other dependencies through IOC

Class PhotoService {

    protected $photosModel = null;

    public function __construct(PhotoInterface $photoModel) {
       $this->photosModel = $photoModel;
    }

    public function getPhotos()
    {
       $photos = Cache::get('photos');

       if (is_null($photos)) {
          return $this->photosModel->getPhotos();
       }
    }
}

solved through IOC

Class PhotoService {

    protected $photosModel = null;

    public function __construct(PhotoInterface $photoModel) {
       $this->photosModel = $photoModel;
    }

    public function getPhotos(CacheInterface $cache)
    {
       $photos = $cache->get('photos');

       if (is_null($photos)) {
          return $this->photosModel->getPhotos();
       }
    }
}

Best example in my point of view the case when externalizing your code, even when you share it between your own projects. It is way more easy for the new implementation to work if it is provided the full signature through an interface, rather than having to look through old code or tests for any facades.

I don't see any harm in using Facades in the controller though.

This kind of setup offers only advantages, between them:

  • the ability to switch cache strategies without headeaches
  • the ability to switch database types
  • the ability to switch features off by injecting a mock through ioc
  • encourages tdd by ease of implementation
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!