Dependency injection with Laravel Facade

2019-08-29 11:00发布

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条回答
Evening l夕情丶
2楼-- · 2019-08-29 11:26

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;
}
查看更多
登录 后发表回答