0

I am currently working on a web app that has been set up using the Repository/Service Layer Design Pattern, i.e. I have service layer that does any necessary business logic before running any methods within the repository. I have facades for each one of my models which access their respective service layers, and this has been fine for the most part. However, now that I am trying to set up Eloquent relationships, the facades seem to be causing a massive headache as I am not sure which direction I should be going.

Take the following code:

class Account extends Eloquent {

    // Our table name
    protected $table = "accounts";

    // Our primary key
    protected $primaryKey = "id";

    /**
     *  Role Relationship
     *
     *  Returns a list of roles associated with 
     *  this account
     */
    public function roles() {
        return $this->hasMany('Role');
    }

}

This will not work as is, because instead of using the entity class of Role, it is using the Role Facade. I have figured out a workaround for this, by setting an alias for the Entity with a slightly different name, such as RoleEntity so that

    public function roles() {
        return $this->hasMany('RoleEntity');
    }

will work, however this doesn't seem like the most optimal solution.

My question is, is the practice ok? Or better yet, should this be happening at all? And if not, how do I fix it/where did I go wrong?

Ryan Brenner
  • 35
  • 1
  • 1
  • 5
  • 1
    I suggest you put your models and facades in different namespaces and reference the model like `App\Models\Role` – lukasgeiter Jan 09 '15 at 21:46

1 Answers1

1

You have two classes with the same name in the same namespace. Use different namespaces so you can use the same class names.

I usually use \Models to locate my models classes.

At the top of each model file:

namespace Models;

In your controller or any part of your app:

\Models\Role::first();

Note that changing the namespace on your model will require you to add the namespaces of other classes i.e. Str, Eloquent, Url, Redirect, etc.

use Eloquent;
use URL;

In your model, you also have to pass the namespaces in the relationship functions, i.e.:

public function roles() {
    return $this->hasMany('\Models\Role');
}
Marco Florian
  • 929
  • 1
  • 10
  • 18
  • Thank you for your help. I actually am using different namespaces for each class. For my Account class (and any other models like it) I am using "namespace Entities;" and for my facades I am using "namespace Services\\(name of model);", i.e. "namespace Services\Account;". That said, doing something like "return $this->hasMany('\Entities\Role');" does seem to work, and while it doesn't seem like an ideal solution, it should work for now. – Ryan Brenner Jan 12 '15 at 16:23
  • Ok, adding it to the answer. Also, why isnt it an ideal solution? – Marco Florian Jan 14 '15 at 13:31