neilcrookes
neilcrookes

Reputation: 4203

Extending Laravel Package Models in app, and having the package controller use them rather than the package model

I've a whole bunch of Laravel 4 packages that provide basic functionality for things like adding simple content managed pages to an app, and another for adding customer testimonials.

The packages include the migrations, models, controllers, routes and sample views and partials that make adding them to a project really quick and easy.

In my current project, I have to add a belongsTo relationship from pages to testimonials to show a relevant testimonial on specific pages, as selected through the CMS.

I have created a migration to add the field to the pages table, extended the pages package model in my app and added the relationship, and configured the CMS package config file to use my model rather the package's.

The issue I've got now though is the package controller's show method that renders a page given a slug, uses the package's model, rather than the one in my app, that extends the package model.

What's the best way of getting the package controller to use my app's model, rather than the one in the package?

I thought maybe I could update the package (since it is mine) to add the name of the namespaced model file to the config file for the package, which I could then change to my app's model file in my app's version of that config file, and update the package controller to look in the config file instead of hardcoding the name of the package model?

Or maybe I should use the IoC container somehow, but I'm not sure exactly how to go about that? Maybe add a constructor which expects an instance of the package model to be injected into it, but then how to I get the IoC container to inject my app's model instead of the package's model? Does anyone have any advice?

Upvotes: 1

Views: 1248

Answers (1)

neilcrookes
neilcrookes

Reputation: 4203

I figured it out and did it using the IoC container. I updated the package controller as described above to use a constructor which expects an instance of the package model to be injected into it, then added the following to the end of app/start/global.php:

App::bind('Fbf\LaravelPages\PagesController', function() {
    return new Fbf\LaravelPages\PagesController(new Page);
});

Here's the model in my app/models directory

<?php

class Page extends Fbf\LaravelPages\Page {

    public function testimonial()
    {
        return $this->belongsTo('Fbf\LaravelTestimonials\Testimonial');
    }

}

Upvotes: 2

Related Questions