问题
How can I have a plain php object from a third party package inherit all the goodness of Laravels Eloquent models? see below:
The model class below is from a third-party package. It is framework and ORM agnostic, written in plain PHP. I cannot change it, only extend it. (example only)
class APlainPHPModelFromLibrary {
protected $someAttribute;
protected $someOtherAttribute;
//...
public function someFunction()
{
// ...
}
}
And here is my Laravel Eloquent version of this model class. I need to extend Eloquent from this class. Also I need to extend from the above VanillaPHPModel so it can inherit Eloquent's methods. I cant see a way around this.
class MyEloquentModelVersion extends Eloquent ... extends APlainPHPModelFromLibrary { // ??
$guarded = [
'EloquentGoodness',
'EloquentGoodness'
];
public function belongsTo()
{
//...Eloquent goodness
}
public function hasMany()
{
//,..Eloquent Goodness
}
}
回答1:
This is just a suggestion. You'd probably be able to solve it in a multiple other ways.
ThirdPartyServiceProvider.php
<?php
class ThirdPartyServiceProvider extends \Illuminate\Support\ServiceProvider {
public function register() {
$this->app->bind('ThirdPartyService', function($app, $third_party_model) {
return new ThirdPartyService($third_party_model, new MyEloquentModelVersion());
});
}
}
ThirdPartyService.php
<?php
class ThirdPartyService {
public $third_party_model = null;
public $my_eloquent_model_version = null;
function __construct(APlainPHPModelFromLibrary $third_party_model, MyEloquentModelVersion $my_eloquent_model_version) {
$this->third_party_model = $third_party_model;
$this->my_eloquent_model_version = $my_eloquent_model_version;
}
function translate() {
// conversion code
return $this;
}
}
In your controller:
$tpsp = App::make('ThirdPartyServiceProvider', $third_party_model);
$tpsp->translate()->my_eloquent_model_version;
来源:https://stackoverflow.com/questions/27442294/how-to-inherit-eloquents-functionality-on-plain-php-objects