Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 1 year ago.
0

Take a look at this line in Model.php https://github.com/laravel/framework/blob/4.2/src/Illuminate/D...

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);
}
Last updated 1 year ago.
0

Whaooo! State::class is good. I thank you Hendore. Cheers.

Last updated 1 year ago.
0

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?

Last updated 1 year ago.
0

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.

Last updated 1 year ago.
0

Thanks for your elaborate response. I appreciate you. Cheers.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

jwadel jwadel Joined 5 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.