0

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.

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105

1 Answers1

2

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;
}
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
  • can I ask you if is there a way to add a constructor to a facade in Laravel? Becuase how should a __construct() work when the object is accessed throguh Facace? – Mostafa Talebi Sep 18 '14 at 14:21
  • 1
    You don't add the constructor to the facade, add it to the underlying class that the facade is referencing – Jeff Lambert Sep 18 '14 at 14:21