PHP code example of mkd / laravel-state-management
1. Go to this page and download the library: Download mkd/laravel-state-management library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mkd / laravel-state-management example snippets
class UserStore extends StoreContract
{
protected $attributes = [
'user',
'email',
'status'
];
protected $casts = [
'email' => StringCast::class, // Custom cast
];
protected $enums = [
'status' => CustomStatusEnum::class // Use enums for statuses
];
public function default(): array
{
return ['user' => User::find($this->key)]; // Fallback if rehydration fails
}
public function updateUserName($name)
{
$user = $this->getUser();
$user->name = $name;
$user->save();
}
}
use App\Stores\UserStore;
public function handleState(StateManagement $stateManagement)
{
// Retrieve the store and set state values
$userStore = $stateManagement->store(UserStore::class);
$userStore->setUser(User::first());
// Call custom methods to manage store data
$userStore->updateUserName('New Name');
}
$userStore = StateManagement::use(UserStore::class);
$userStore->setKey(1);
$userStore->rehydrate();
$status = $userStore->getStatus(); // Retrieve status from the store
class EmailCast implements StateCastAttribute
{
public function get($model, string $key, $value, array $attributes)
{
return strtolower($value);
}
public function set($model, string $key, $value, array $attributes)
{
return strtoupper($value);
}
}
class UserNotification extends StoreContract
{
protected $attributes = ['user', 'email'];
protected $casts = ['email' => EmailCast::class];
public function sendInvoiceEmail(Invoice $invoice)
{
$this->getUser()->notify(new InvoiceEmail($invoice));
}
}
use App\Stores\UserStore;
public function handleState(StateManagement $stateManagement)
{
$user = User::first();
// Retrieve the store and set state values
$userStore = $stateManagement->store(UserStore::class);
$userStore->setUser($user);
$userStore->setKey($user->id);
// Call custom methods to manage store data
$userStore->updateUserName('New Name');
$userStore->persist();
}
public function persistUsing()
{
//Your own persist logic
//Init custom persist flag
$this->initCustomPersist()
}
use App\Stores\UserStore;
public function handleState(StateManagement $stateManagement)
{
$user = User::first();
// Retrieve the store and set state values
$userStore = $stateManagement->store(UserStore::class);
$userStore->setKey($user->id);
$userStore->rehydrate();
$userStore->getUser()->name // 'New Name'
}
public function rehydrateUsing()
{
// your own rehydrating logic
//Init custom rehydrate flag
$this->initCustomRehydrate();
}
bash
php artisan store-cast:make EmailCast
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.