matt-daneshvar / laravel-survey

Create and manage surveys within your Laravel app.
MIT License
250 stars 50 forks source link

How to properly extend Survey and Entry? #33

Closed LufoX11 closed 2 years ago

LufoX11 commented 2 years ago

Hi! I'm not sure it's something to ask here, but since it's also related to the way you built your component, I'll do.

I'd like to extend Survey and Entry models so I can add more methods inside. I added app/Models/Survey/Survey.php and .../Entry.php models extending those in vendors directory. Everything is working fine, however, I need vendor/.../Models/Entry->survey() and vendor/.../Models/Survey->entries() to map my extended classes instead of those inside the vendor directory. The same for the rest of model relationships related methods. I was be able to achieve this by overriding those specific methods in my model, but I feel this is not the right approach. I also googled it and saw another approaches, but I'm still not convinced since they look like workarounds uglier than mine.

What do you think it's the best I can do to handle this?

Thank you in advance.

Example of what I did:

# app/Models/Survey/Survey.php:

namespace App\Models\Survey;

class Survey extends \MattDaneshvar\Survey\Models\Survey
{
    ...
    public function entries()
    {
        return $this->hasMany(Entry::class); // App\Models\Survey\Entry
    }

}
matt-daneshvar commented 2 years ago

Hi Luciano,

One way to achieve this is to bind your implementation to the correspoding contract that comes with the package. A good place to do this is within the register method of your AppServiceProvider:

use App\Models\Entry;
use MattDaneshvar\Survey\Contracts\Entry as EntryContract;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(EntryContract::class, Entry::class);
    }
    // ...

This way the package will know to resolve your implementation anytime it needs an Entry model, and you won't have to override every relationship method. Does this work for you?

Credit to @mrchimp for implementing this in v0.1.5.

LufoX11 commented 2 years ago

Thank you very much for you soon answer and your time, it worked!!

BTW really nice component, I like how neat and well coded it is :+1:

matt-daneshvar commented 2 years ago

Thanks for reporting back, glad it worked for you ✌️