如何在普通PHP对象上继承Enloquent的功能 [英] How to inherit Eloquent's functionality on plain PHP objects

查看:129
本文介绍了如何在普通PHP对象上继承Enloquent的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用第三方软件包中的一个简单的php对象继承Laravels Eloquent模型的所有优点?

How can I have a plain php object from a third party package inherit all the goodness of Laravels Eloquent models? see below:

下面的模型类是来自第三方软件包框架和ORM不可知,以纯PHP 编写。我不能改变它,只能扩展它。 (仅示例)

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()
    {
        // ...
    }
}

这里是我的Laravel雄辩版本的这个模型类。我需要从这个类中扩展口述。另外我需要从上面的VanillaPHModel扩展,所以它可以继承Eloquent的方法。我不能看到这个方法。

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
    }
}   


推荐答案

这只是一个建议。您可能可以通过其他方式解决问题。

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 / p>

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;
        }
    }

在您的控制器中:

$tpsp = App::make('ThirdPartyServiceProvider', $third_party_model);

$tpsp->translate()->my_eloquent_model_version;

这篇关于如何在普通PHP对象上继承Enloquent的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆