How to inherit Eloquent's functionality on plain PHP objects

人盡茶涼 提交于 2019-12-13 00:42:18

问题


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

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