johnnyfreeman / laravel-custom-relation

A custom relation for when stock relations aren't enough.
78 stars 28 forks source link

Api Proposal #9

Open johnnyfreeman opened 4 years ago

johnnyfreeman commented 4 years ago

Now that #8 has been merged, I feel like we've learned the best way to tackle the issue of making a custom relation is by accepting callables/closures for the abstract Relation methods rather than trying to find an implementation that fits every scenario. I don't like the readability of it though...

class User extends Model
{
    use HasCustomRelations;

    public function someOtherRelation()
    {
        return $this->custom(
            SomeOtherModel::class,
            function (...) {
                // ...
            },
            function (...) {
                // ...
            },
            function (...) {
                // ...
            },
            function (...) {
                // ...
            },
        );
    }
}

Seems cluttered and I forget which Closure is which and have to reference the package. The introduction of a new RelationBuilder object might be helpful for readability. Something like this...

class User extends Model
{
    use HasCustomRelations;

    public function someOtherRelation()
    {
        return $this->buildRelation()
            ->related(SomeOtherModel::class)
            ->addConstraints(function (...) {
                // ...
            })
            ->addEagerConstraints(function (...) {
                // ...
            })
            ->initRelation(function (...) {
                // ...
            })
            ->match(function (...) {
                // ...
            })
            ->getRelation();
    }
}

While I like this better, my question now becomes, is this any better than just creating a new class that for each custom relation? Then you can just do this.

class User extends Model
{
    use HasCustomRelations;

    public function someOtherRelation()
    {
        return new MyCustomRelation(SomeOtherModel::query(), $this);
    }
}

I guess on one hand you would have potentially a large amount of custom classes/files that just describe a single custom relationship, and on the other hand, you have a potentially large amount of these verbose RelationBuilder methods on your models.

Maybe there's room for both? What are your thoughts?

DivineAlien commented 4 years ago

for a beginner like me

class User extends Model
{
    use HasCustomRelations;

    public function someOtherRelation()
    {
        return new MyCustomRelation(SomeOtherModel::query(), $this);
    }
}

is more cleaner.

I want to help but I don't know about this topic and objects. can you give me some links or some words to search on internet. so maybe I will be usefull?