简体   繁体   中英

Extending Laravel 4 Eloquent models from within packages

first of all I'm new to IoC, ServiceProviders and Facades, but I'm guessing the answer lies in those for the following:

What would be the best way to extend Eloquent models from within packages (there are probably more than just one right way, but please do share yours). Here's the application structure I'm planning to have:

L4 framework + two separate packages (CMS & CRM), that will need to share some Eloquent models. However, there might be package specific cases where the package needs to extend the Eloquent model that's being used by both and I wouldn't like to touch the base model.

I'm also planning on using separate controllers and views for each package (unless there's something that will certainly be the same across packages). Master view will be loaded from the L4-views folder. Does this sound right? (At least I played with separate controllers and views already and they worked out fine.)

The reason I want to go with the package approach is that I want the CMS & CRM to be independent code and structure-wise so they can easily be installed & uninstalled & updated via composer.

I'd be more than delighted with any suggestions on achieving all this. Also, if this doesn't seem to make any sense at all, let me know and I'll try to clarify myself :)

Cheers!

If you creating a package within Laravel 4 then you should be able to do something like this:

<?php

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model {

    // Your code here
}

Note: I was a little unsure on whether you wanted to extend Eloquent or a model you created yourself that extends eloquent?

According to your comment above, I would consider namepacing to be the correct answer since your models will be sharing functionality and it makes more sense to have them in the same installation rather than separate packages. Here's an example:

in /app/models/Entities/CRM/UserEntity.php

<?php namespace Project\Models\Entities\CRM;

use Eloquent;

Class User extends Eloquent {
    ...
    public function owner()
    {
        return $this->belongsTo('Project\Models\Entities\CMS\User');
    }
}

in /app/models/Entities/CMS/UserEntity.php

<?php namespace Project\Models\Entities\CMS;

use Eloquent;

Class User extends Eloquent {
    ...
    public function contacts()
    {
        return $this->hasMany('Project\Models\Entities\CRM\User');
    }
}

Not to mention that you should populate the Models namespace in your composer.json

{
   ...
    "autoload":{
        "psr-0": { "Project\\Models": "app/models/" }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM