Dhosa allows developers to implement hot-swapping capabilities on Eloquent models. This will helps package developer to create a base model and app developer can extends upon the base model while making sure that all the relationship uses the proper model.
To install through composer, run the following command from terminal:
composer require "laravie/dhosa"
To enable hot-swap to any Eloquent all you need to do is use Laravie\Dhosa\Concerns\Swappable
and implements the method.
<?php
namespace App\Models;
// ...
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravie\Dhosa\Concerns\Swappable;
class User extends Authenticatable
{
use Swappable;
/**
* Get Hot-swappable alias name.
*
* @return string
*/
public static function hsAliasName(): string
{
return 'User';
}
}
use Laravie\Dhosa\HotSwap;
HotSwap::register('Orchestra\Model\User');
In the App\Providers\AppServiceProvider
we can now override the resolution of User
to App\User
by adding:
use Laravie\Dhosa\HotSwap;
HotSwap::override('User', 'App\User');
You can define relationship by using the following code:
use Orchestra\Model\User;
/* ... */
public function user()
{
return $this->belongsTo(User::hsFinder());
}
use Orchestra\Model\User;
$user = User::hs(); // return instance of App\User
$user = User::hs()->query(); // return a query builder for App\User
$user = User::hsOn('api'); // return a query builder for App\User using `api` db connection.
$user = User::hsOnWriteConnection(); // return a query builder for App\User using write PDO connection.
use Orchestra\Model\Role;
use Orchestra\Model\User;
User::hsAliasName(); // return "User"
User::hsFinder(); // return "App\User"
Role::hsFinder(); // return "Orchestra\Model\Role"