PHP code example of jcesarbueno / laravel-strategy
1. Go to this page and download the library: Download jcesarbueno/laravel-strategy 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/ */
jcesarbueno / laravel-strategy example snippets
use App\Strategies\SendNotification\Factories\SendNotificationFactory;
use App\Models\Customer;
$notificationType = Customer::find(1)->notification_type;
// Choose the implementation in runtime
$sendNotification = SendNotificationFactory::make($notificationType);
$sendNotification->send();
namespace App\Strategies\SendNotification\Pipelines;
use Closure;
class EnsureNotificationTextIsNotEmpty
{
public function handle($customer, Closure $next)
{
if (empty($customer->event->text)) {
throw new \Exception('Notification text cannot be empty');
}
return $next($customer);
}
}
namespace App\Strategies\SendNotification\Pipelines;
use Closure;
class EnsureCustomerHasEmail
{
public function handle($customer, Closure $next)
{
if (empty($customer->email)) {
throw new \Exception('Customer must have an email');
}
return $next($customer);
}
}
public function getPipelines(): array
{
return [
EnsureNotificationTextIsNotEmpty::class,
EnsureCustomerHasEmail::class,
];
}
public function getPipelines(): array
{
return [
EnsureNotificationTextIsNotEmpty::class,
];
}
use App\Strategies\SendNotification\Factories\SendNotificationFactory;
use App\Models\Customer;
use Illuminate\Support\Facades\Pipeline;
$customer = Customer::find(1);
$sendNotification = SendNotificationFactory::make($customer->notification_type);
Pipeline::send($customer)
->through($sendNotification->getPipelines())
->then(function ($customer) use ($sendNotification) {
$sendNotification->send();
});
namespace App\Strategies\SendNotification\Pipelines;
use Illuminate\Support\Collection;
use Closure;
class FilterNotSendedEvents
{
public function handle(Collection $events, Closure $next)
{
$events->filter(function ($event) {
return $event->sended === false;
});
return $next($events);
}
}
use App\Strategies\SendNotification\Factories\SendNotificationFactory;
use App\Models\Customer;
use Illuminate\Support\Facades\Pipeline;
$customer = Customer::with('events')->find(1);
$sendNotification = SendNotificationFactory::make($customer->notification_type);
$filteredEvents = Pipeline::send($customer->events)
->through($sendNotification->getPipelines())
->thenReturn();
$sendNotification->send($filteredEvents);