Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Relating Models in Module
  • I'm not sure if I am missing something, but after moving my blog MVC from app path into a module, I had to add a prefix when setting up the relationship using ORM like so: 'model_to' => 'blog\Model_Comment', is that the best practice?

    /**
    * Post HasMany Comments
    * @var array
    */
    protected static $_has_many = array(
    'comments' => array(
    'key_from' => 'id',
    'model_to' => 'blog\Model_Comment',
    'key_to' => 'post_id',
    'cascade_save' => false,
    'cascade_delete' => true, // We delete all comments from the post deleted
    ),
    );
  • Since a module implies a namespace, yes, you need to prefix every class with the namespace, unless you're inside the module.

    Having said that, the idea behind modules is loose coupling. You should be able to take any module, throw it into another application, and it should work (or die gracefully).

    By doing this, you introduce a tight coupling with the module, which will cause misery if you remove the module, or replace it by a module called 'betterblog'.

    We solve this by having a central repository of modules, which uses logical names that are mapped to module names, and which lists the functionality of each module. Then (given your example) in the _init() of the Model we call the repository to check if a module with logical name "blog" exists, and if that provides a functionality called "comments". If so, we dynamically add this relation. If not, we add a dummy model to the relation (which is an empty table with only an 'id' column) so that any code using the relation will not break, it will just never produce a result.

    This is part of our app framework, with which we start every new application, and it makes modules completely pluggable. Over time you end up with lots of modules, and application development becomes very quick, since a lot of functionality is already on the shelf...
  • Hmm. Without prefixing my model like so 'model_to' => 'blog\Model_Comment', I got a nasty error. Could I be missing something in my model's init() method? Should I add a init() method of my own
  • HarroHarro
    Accepted Answer
    Yes, because it's not a class reference, it's a string. Class names in strings don't inherit the current namespace (simply because where you define it could be not where you use it), so they always are from global.

    In short, in a string you always have to define the full namespace.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion