How to add functionality to an existing entry model (from a vendor package)

pepijn - 7 months ago

I had to extend the Users module to add a few fields. Because I didn't want to touch core functionality (or mess around in vendor folders), I instead created a new stream based module, called Profiles. A Profile belongsTo a User (so there's a user_id column on the profiles table)

Now, oftentimes in my code I need to find a profile based on a user_id. I currently created a Facade for this, which contains a function similar to the below:

    /**
     * Returns the profile of the given userId
     */
    public function fromUser($userId) {
        return ProfileModel::where('user_id', $userId)->first();
    }

However, using this approach, I cannot use some great laravel concepts, like eager loading. What I really want to do, is augment the /** * Returns the profile of the given userId */ public function fromUser($userId) { return ProfileModel::where('user_id', $userId)->first(); } class, and add the following relationship:

// Anomaly\UsersModule\User\UserModel.php
public function profile() {
    return $this->hasOne(ProfileModel::class, 'user_id', 'id');
}

How can I do this without touching the core package ?

huglester - 7 months ago

Hello,

I think you can add a $singleton in the 'config/streams.php', file. Which would override the : Anomaly\UsersModule\User\UserModel like so: 'singletons' => [ '\Anomaly\UsersModule\User\UserModel' => '\App\Extensions\User\UserModel', ],

Later \App\Extensions\User\UserModel' should extend '\Anomaly\UsersModule\User\UserModel', and add those missing methods there. it SHOULD work I think.

have a good luck :)

pepijn - 7 months ago

@hughlester Sounds plausible ! Will try that out today!


Edit: tried it out, but to no avail. :/