We have some options:
Dependency Injection:
use ExternalClass;
class Model extends Eloquent {
private $external;
public function __construct(ExternalClass $external)
{
$this->external = $external;
}
public function doWhatever()
{
return $this->external->do();
}
public function __call($name, $arguments)
{
return call_user_func_array(array($this->external,$name), $arguments);
}
}
You don't have to pass a class to your model, Laravel will try to instantiate and inject that class for you.
edit
And you don't have to rewrite all methods, see this magic method __call? It will be fired automatically by PHP everytime a method is not found in your class, so you can use it to forward that call to your external class.
end-edit
Traits: (this is PHP 5.4+)
class Model extends Eloquent {
use MyTraits;
public function doWhatever()
{
return $this->do();
}
}
trait MyTraits {
public function do()
{
/// this metho will be available in your class
}
}
You can also use the Repository Pattern:
class DataRepository {
private $user;
private $external;
public function __construct(User $user, ExternalClass $external)
{
$this->user = $user;
$this->external = $external;
}
public function allUsers()
{
return $this->user->all();
}
public function doWhatever()
{
return $this->external->do($this->user);
}
}
There some others, but your project is what will really tell you what's best.
EDIT
Note that you have to be aware of the __call magic method, because Laravel also uses it to deliver dynamic methods, like whereColumnname() and you risk breaking by using it. But this is also something you can circumvent with a little more code:
public function __call($name, $arguments)
{
// If the method is not one of your package ones, try execute an Eloquent (parent) one
if ( ! in_array($name, ['methodA', 'methodB', 'methodC']))
{
return parent::__call($name, $arguments);
}
else
{
return call_user_func_array(array($this->external,$name), $arguments);
}
}