Take a look at this line in Model.php https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L849
Drawback with your method would be creating an additional instance of State whenever using this relationship, what you are essentially doing is:
class A {
...
}
$a = new A;
$b = new $a;
If you don't want to specify the full namespaced class name in a string within your relations, you can use the class static property:
public function states() {
return $this->hasMany(State::class);
}
Whaooo! State::class is good. I thank you Hendore. Cheers.
However, is this whole process not going against the Single Responsibility principle; having a class instantiating or reference the static property of another.
Is this testable?
jwadel said:
However, is this whole process not going against the Single Responsibility principle; having a class instantiating or reference the static property of another.
Is this testable?
The class static property is just a string of the fully qualified name of the class, it's not really different when compared to using
return $this->hasMany('Acme\\Module\\SomeModel');
Only difference with using SomeClass::class is that class need's to be in the same namespace otherwise you would have to either add a use statement or specify the full namespaced class anyway, which in that case it's quicker and less keystrokes to use a string literal
// With use statement for model in a different namespace
use Acme\Module\SomeModel
$this->hasMany(SomeModel::class);
// Without use statement for model in a different namespace
$this->hasMany(\Acme\Module\SomeModel::class)
// or
$this->hasMany('Acme\\Module\\SomeModel');
Take your pick, they all do the same job.
Thanks for your elaborate response. I appreciate you. Cheers.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community