Dependency injection with Laravel Facade

此生再无相见时 提交于 2019-12-13 05:01:30

问题


I have an error class which I have made a Facade and a ServiceProvider for.

I use it like this:

Err::getLastError();

I have also another class for file validation:

FileValidate::IsImage($this->getUpload());

I want to inject the Err facade into the FileValidate so that I use it like this:

FileValidate::Error()->getLastError();

How should I do this?

Now My approach is that, in FileValidate class I add a member:

function Error()
{
   return $this;
}

Though the above just returns the FileValidate object, thus I add another method:

function getLastError()
{
    return   Err::getLastError();
}

But then for each method of Err, I should make an alternative in FileValidate and all Err like the above example. I need a more dynamic solution.


回答1:


In your FileValidate::Error() method return the error class rather than an instance of FileValidate:

function Error()
{
    return app()->make('Err');
}

This will return your error object which should have whatever methods on it that you need without having to duplicate them on another class for no reason.

Another alternative could be to add the error object into the FileValidate's constructor:

public function __construct(Err $error) {
    $this->$error = $error;
}

After updating your file validate's service provider, you could then just return that object from your Error method:

public function Error()
{
    return $this->error;
}


来源:https://stackoverflow.com/questions/25914976/dependency-injection-with-laravel-facade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!