Laravel Architecture
Architecture gives a Laravel application five small building blocks: Actions for use cases, Tasks for reusable steps, Services for business, integration and module-boundary capabilities, Data objects for typed input and output, and Contexts for state shared during one operation. Each one is a plain abstract class built on what Laravel already ships: the service container, the pipeline, FormRequest validation and Eloquent serialization. Nothing intercepts your calls, wraps your results or enforces rules at runtime.
Actions and Tasks
One class per use case or step, resolved through the container and callable directly or as an invokable.
Task Pipelines
An Action sends a payload through Tasks with Laravel's own pipeline: closures, classes and parameters included.
Three Service Categories
Business, Integration and Boundary services share one base class; the category is a convention, not a type.
Typed Data Objects
Hydrated through the constructor from arrays, requests and models, with strict types and no silent coercion.
Mapping and Collections
MapName renames fields, Hidden keeps them out of JSON, and DataCollection hydrates lists of nested Data.
Generators
make:action, make:task, make:service, make:data and make:context, with nested names and custom paths.
Start with one Action per use case and call it from your controller. Add Tasks, Services and a Context only when the use case grows enough to need them.
#Installation
Install the package with Composer; the service provider registers itself. There is no configuration file to publish.
#Requirements
- PHP >= 8.0
- Laravel >= 7.30
#Composer Installation
composer require pharaonic/laravel-architecture#Create Your First Action
php artisan make:action CreateOrderThe command writes app/Actions/CreateOrderAction.php, with the namespace your composer.json maps to app/.
#Publish the Stubs (optional)
Publish the generator stubs when you want every generated class to start from your own template.
php artisan vendor:publish --tag=architecture-stubsThe stubs are copied to stubs/architecture. See Generators for the details.
You're all set! Extend Pharaonic\Laravel\Architecture\Action, Task, Service, Data or Context in your own classes, or let the generators write them for you.
#Basic Usage
A use case is an Action. It takes typed input, often a Data object, and returns its result.
1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class OrderData extends Data 6{ 7 public function __construct( 8 public int $customerId, 9 public string $product,10 public int $quantity = 1,11 ) {}12} 1namespace App\Actions; 2 3use App\Data\OrderData; 4use App\Order; 5use Pharaonic\Laravel\Architecture\Action; 6 7class CreateOrderAction extends Action 8{ 9 public function handle(OrderData $data): Order10 {11 return Order::create([12 'customer_id' => $data->customerId,13 'product' => $data->product,14 'quantity' => $data->quantity,15 ]);16 }17}Call the Action from a controller, a job, a command or a listener. make() resolves it through the container, so its constructor dependencies are injected for you.
1public function store(Request $request)2{3 $order = CreateOrderAction::make()->handle(OrderData::fromRequest($request));4 5 return redirect()->route('orders.show', $order);6}The same Action can be type-hinted, built with new, or invoked:
1public function store(Request $request, CreateOrderAction $createOrder)2{3 $order = $createOrder(OrderData::fromRequest($request)); // same as ->handle(...)4}#The Five Building Blocks
| Class | Use it for | Exposes |
|---|---|---|
Action |
A complete use case, such as creating an order | make(), __invoke(), tasks() |
Task |
A small reusable step, such as calculating a total | make(), __invoke() |
Service |
A Business, Integration or Boundary capability | make() |
Data |
Typed data passed between layers | fromArray(), fromRequest(), fromModel(), toArray(), toJson(), with() |
Context |
Mutable state shared during one operation | nothing: it is a marker class |
Each class works on its own. You can add Actions to an existing application without Tasks, Services or Data, and without moving any code into modules.
#Actions
An Action represents one complete use case with a clear business outcome, such as creating an order or cancelling a subscription. It is the entry point your controllers, jobs, Artisan commands and listeners call.
#Defining an Action
Extend Action and add a public handle() method. The base class declares no handle(), so you choose its parameters and return type freely.
1namespace App\Actions; 2 3use App\Order; 4use App\Services\Integration\StripeGatewayService; 5use Illuminate\Support\Facades\DB; 6use Pharaonic\Laravel\Architecture\Action; 7 8class CancelOrderAction extends Action 9{10 public function __construct(protected StripeGatewayService $stripe) {}11 12 public function handle(Order $order, string $reason = 'customer'): Order13 {14 DB::transaction(function () use ($order, $reason) {15 $order->update(['status' => 'cancelled', 'cancel_reason' => $reason]);16 $order->items()->update(['reserved' => false]);17 });18 19 $this->stripe->refund($order->charge_id);20 21 return $order;22 }23}Actions add no automatic transaction. Wrap the database writes that must succeed or fail together in DB::transaction() yourself. A rollback never undoes external effects such as a refund or an email, so keep those outside the transaction.
#Creating an Action
make() resolves the called class through Laravel's service container, like app()->make(CancelOrderAction::class, $parameters). StripeGatewayService is defined in Services.
1use GuzzleHttp\Client;2 3$action = CancelOrderAction::make();4 5// Override constructor parameters by name; the rest are still resolved.6$action = CancelOrderAction::make(['stripe' => new StripeGatewayService(new Client(['timeout' => 5]))]);Container bindings are respected: if you bind or mock CancelOrderAction, make() returns that instance. No singleton or scoped lifetime is imposed. Passing parameters always builds a new instance, as Laravel's container does.
You can also build an Action with new, or type-hint it anywhere Laravel injects dependencies.
#Calling an Action
handle() and the invokable form run the same code and return the same result.
1$action->handle($order, 'fraud');2$action($order, 'fraud');3$action($order, reason: 'fraud'); // named arguments are forwardedA void handler returns null through __invoke(). Exceptions propagate unchanged. Calling an Action that has no handle() method throws a BadMethodCallException.
__invoke() forwards its arguments through a variadic parameter, so a handle() that takes a parameter by reference (&$value) only receives a copy when invoked. Call handle() directly when you need the reference.
#Running Tasks Through a Pipeline
An Action can send a payload through a list of Tasks with the protected tasks() method, which uses Laravel's Illuminate\Pipeline\Pipeline. See Task Pipelines for the pipe signature; OrderContext and the three Tasks are defined in Contexts.
1namespace App\Actions; 2 3use App\Contexts\OrderContext; 4use App\Order; 5use App\Tasks\CalculateTotalTask; 6use App\Tasks\CreateOrderTask; 7use App\Tasks\ReserveStockTask; 8use Illuminate\Support\Facades\DB; 9use Pharaonic\Laravel\Architecture\Action;10 11class PlaceOrderAction extends Action12{13 public function handle(OrderContext $context): Order14 {15 return DB::transaction(function () use ($context) {16 return $this->tasks($context, [17 CalculateTotalTask::class,18 ReserveStockTask::class,19 CreateOrderTask::class,20 ])->order;21 });22 }23}#Guidelines
- Keep one use case per Action: creating and cancelling an order are two Actions.
- An Action may call Tasks and Services, query models directly, and call another Action of the same module when it is justified.
- Avoid circular calls between Actions.
#Tasks
A Task is a small, focused operation that several use cases can reuse, such as calculating an order total. It is not a complete use case on its own.
#Defining a Task
A Task works like an Action: extend Task, add a public handle() method, and inject dependencies through the constructor.
1namespace App\Tasks; 2 3use App\Services\Business\PricingService; 4use Pharaonic\Laravel\Architecture\Task; 5 6class CalculateSubtotalTask extends Task 7{ 8 public function __construct(protected PricingService $pricing) {} 9 10 public function handle(array $items): float11 {12 return array_sum(array_map(fn (array $item) => $this->pricing->price($item), $items));13 }14}1$items = [['sku' => 'A-1', 'price' => 50.0, 'quantity' => 2]];2 3$subtotal = CalculateSubtotalTask::make()->handle($items); // 100.04$subtotal = CalculateSubtotalTask::make()($items);PricingService is defined in Services. make(), __invoke(), named arguments, void handlers and exceptions behave exactly as they do on an Action. Tasks have no tasks() method.
#Task Pipelines
A Task used in a pipeline is still a regular Task: give its handle() the signature Laravel's pipeline expects, take the payload, and pass it on with $next. This one works on the OrderContext defined in Contexts.
1namespace App\Tasks; 2 3use App\Contexts\OrderContext; 4use Closure; 5use Pharaonic\Laravel\Architecture\Task; 6 7class CalculateTotalTask extends Task 8{ 9 public function handle(mixed $payload, Closure $next): mixed10 {11 /** @var OrderContext $payload */12 $payload->total = collect($payload->items)->sum(fn ($item) => $item['price'] * $item['quantity']);13 14 return $next($payload);15 }16}php artisan make:task CalculateTotal --pipeline writes this shape for you.
An Action runs the pipeline with $this->tasks($payload, $tasks). The behavior is Laravel's own pipeline:
| Pipe | How it runs |
|---|---|
| A class name | Resolved through the container, then handle($payload, $next) |
Class:first,second |
Same, with 'first' and 'second' passed after $next |
| An object | handle($payload, $next) when it has one, otherwise __invoke($payload, $next) |
| A closure | fn ($payload, Closure $next) => ... |
- Pipes run in the order you list them, and each receives what the previous one passed to
$next. - A pipe may change the payload or replace it entirely; the pipeline returns what the last pipe returns.
- A pipe that returns without calling
$nextstops the pipeline: its return value is the result, evennull. - An empty list returns the payload unchanged. Exceptions propagate.
- The payload can be anything: a Context, a Data object, a model, an array, a scalar or
null.
Any class, object or closure Laravel's pipeline accepts works in tasks(). Extending Task simply gives the class make() and an invokable form for use outside a pipeline.
#Guidelines
- Tasks may call other Tasks of the same module, Services, models and the database.
- Tasks should not call Actions.
#Services
A Service groups a capability behind ordinary public methods. Every service extends the same Service class, which only adds make().
1namespace App\Services\Business; 2 3use Pharaonic\Laravel\Architecture\Service; 4 5class PricingService extends Service 6{ 7 public function price(array $item): float 8 { 9 return $item['price'] * $item['quantity'];10 }11 12 public function withTax(float $amount, float $rate): float13 {14 return round($amount * (1 + $rate), 2);15 }16}1$pricing = PricingService::make();2$pricing->withTax($pricing->price(['price' => 50.0, 'quantity' => 2]), 0.14); // 114.0An Integration service wraps one external system. This one talks to Stripe's HTTP API with Guzzle, which Laravel 7 applications install by default.
1namespace App\Services\Integration; 2 3use GuzzleHttp\Client; 4use Pharaonic\Laravel\Architecture\Service; 5 6class StripeGatewayService extends Service 7{ 8 public function __construct(protected Client $http) {} 9 10 public function charge(string $customerId, int $amountInCents): string11 {12 return $this->send('charges', [13 'customer' => $customerId,14 'amount' => $amountInCents,15 'currency' => 'usd',16 ]);17 }18 19 public function refund(string $chargeId): string20 {21 return $this->send('refunds', ['charge' => $chargeId]);22 }23 24 private function send(string $endpoint, array $parameters): string25 {26 $response = $this->http->post('https://api.stripe.com/v1/'.$endpoint, [27 'auth' => [config('services.stripe.secret'), ''],28 'form_params' => $parameters,29 ]);30 31 return json_decode((string) $response->getBody(), true)['id'];32 }33}A Service has no handle() and is not invokable. Define as many public methods as the capability needs, with any signatures. Statelessness is recommended but not required.
#Categories
There are three categories of Service. They are a convention for responsibilities and folders; all of them extend the same class, and nothing checks the category at runtime.
| Category | Responsibility | Default folder |
|---|---|---|
| Business | Cohesive internal business capabilities: reads, writes and business rules, without orchestrating a whole use case | app/Services/Business |
| Integration | Talking to external APIs, SDKs and systems: communication, authentication, data transformation, integration errors | app/Services/Integration |
| Boundary | The thin public interface of a module, which other modules call instead of its internal classes | app/Services/Boundary |
php artisan make:service Pricing # Business (the default)php artisan make:service Stripe --integrationphp artisan make:service Orders --boundary#Guidelines
- Business services may use Integration and Boundary services and the database. They should not call Actions, Tasks or other Business services.
- Integration services should stay independent of Actions, Tasks and other Services. They may store integration state, such as access tokens, in the database.
- Boundary services may delegate to the Actions, Tasks and Business services their own module owns, or do simple local work. Avoid calling other Boundary or Integration services from them.
#Dependency Guidelines
These recommendations describe which component should call which directly. They are documentation only: the package does not validate or enforce them, and they are not a required call sequence.
| Caller | Action | Task | Business | Integration | Boundary | Model / DB |
|---|---|---|---|---|---|---|
| Action | Same module | Same module | Allowed | Allowed | Allowed | Allowed |
| Task | Discouraged | Same module | Allowed | Allowed | Allowed | Allowed |
| Business | Discouraged | Discouraged | Discouraged | Allowed | Allowed | Allowed |
| Integration | Discouraged | Discouraged | Discouraged | Discouraged | Discouraged | Integration needs only |
| Boundary | Own module | Own module | Own module | Discouraged | Discouraged | Own module |
- "Same module" applies to internal Actions, Tasks, Business services and models.
- Integration dependencies should respect module ownership or explicitly public contracts.
- A Boundary dependency means the other module's public Boundary service.
- Avoid circular dependencies, including indirect cycles across modules.
- Pass Data and Context objects explicitly where they help.
#Validation and Authorization
Validate input where it arrives, usually in a FormRequest, before it reaches an Action. Business validation and authorization may live in Actions, Tasks or Services. Use Laravel's validation, authorization and exceptions: the package adds no validation API, result wrapper or required return type.
"Module" here means any folder of related code you choose. The package does not require a modules package; generators accept a --path for any PSR-4 folder.
#Data Objects
A Data object carries structured, typed data between layers. Declare its fields as constructor-promoted public properties; immutable objects are recommended but not required.
1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class UserData extends Data 6{ 7 public function __construct( 8 public string $name, 9 public string $email,10 public bool $active = true,11 ) {}12}Keep business logic and execution state out of Data objects: they describe values, and a Context holds state.
#From an Array
fromArray() builds the object through its constructor, matching array keys to constructor parameter names. Key order does not matter.
1$user = UserData::fromArray([3 'name' => 'Ahmed',4 'role' => 'admin', // ignored: not a constructor parameter5]);6 7$user->active; // true (the constructor default)| Input | Result |
|---|---|
| Extra keys | Ignored |
| A missing parameter that has a default | The default is used |
| A missing parameter without a default | InvalidArgumentException, even when its type is nullable |
null |
Accepted only when the type allows null |
| A value of the wrong type | TypeError: values are never coerced, so '2' is not an int (an int still widens to float, as in PHP) |
The constructor always runs, and no dynamic properties are created. There is no validation engine: validate input before building the object, for example with a FormRequest.
#From a Request
fromRequest() uses validated() when the request is a FormRequest, and all() for any other request.
1namespace App\Http\Requests; 2 3use Illuminate\Foundation\Http\FormRequest; 4 5class StoreUserRequest extends FormRequest 6{ 7 public function rules() 8 { 9 return [10 'name' => 'required|string|max:255',11 'email' => 'required|email',12 ];13 }14} 1namespace App\Http\Controllers; 2 3use App\Data\UserData; 4use App\Http\Requests\StoreUserRequest; 5 6class UserController extends Controller 7{ 8 public function store(StoreUserRequest $request) 9 {10 $user = UserData::fromRequest($request); // only name and email11 12 // ...13 }14}For an ordinary Illuminate\Http\Request, fromRequest() uses every input field as is. To build from input you validated yourself, pass it to fromArray(): UserData::fromArray($request->validate([...])).
#From a Model
fromModel() is fromArray($model->toArray()), so Eloquent decides what is included: casts, accessors in $appends, $hidden and $visible, and relations that are already loaded.
1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class ProfileData extends Data 6{ 7 public function __construct( 8 public string $name, 9 public string $email,10 public ?AddressData $address = null, // filled when the relation is loaded11 ) {}12}1$profile = ProfileData::fromModel($user->load('address'));It never loads relations on its own and never reveals hidden attributes. Accessors run as part of Eloquent's serialization.
#Nested Data
A parameter typed with a concrete Data class is built from an array automatically; an instance of that class is accepted as is.
1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class AddressData extends Data 6{ 7 public function __construct( 8 public string $city, 9 public ?string $street = null,10 ) {}11} 1class PersonData extends Data 2{ 3 public function __construct( 4 public string $name, 5 public AddressData $address, 6 public ?AddressData $billing = null, 7 ) {} 8} 9 10$person = PersonData::fromArray([11 'name' => 'Ahmed',12 'address' => ['city' => 'Alexandria'],13]);14 15$person->address->city; // "Alexandria"Union types such as AddressData|array are never guessed: the value is passed to the constructor unchanged. For lists of Data, use the DataCollection attribute.
#Serialization
toArray() returns the object's initialized public properties, with nested Data, arrays and collections converted recursively. jsonSerialize() returns the same array, and toJson() encodes it.
2$user->toJson(JSON_PRETTY_PRINT); // your JSON options are respected3return response()->json($user); // Data is JsonSerializable- Static, protected and private properties are never included, and no getter is called.
- A typed public property that was never initialized is left out instead of failing.
- Values implementing
Arrayable, such as models and collections, are converted with their owntoArray(), as Laravel's collections do. Other objects are left forjson_encode. toJson()throws aJsonExceptionwhen the data cannot be encoded, for example invalid UTF-8; it never returnsfalse.- A Data object that contains itself throws a
LogicExceptioninstead of recursing forever.
#Updating a Copy
with() returns a new instance of the same class with some fields replaced, and leaves the original unchanged.
1$updated = $user->with(['name' => 'Mohamed']);2 3$user->name; // "Ahmed"4$updated->name; // "Mohamed"- Use PHP property names, not
MapNamenames. An unknown key throwsInvalidArgumentException. - Every other field is copied from the current object, including hidden and protected promoted properties.
- New values follow the same rules as
fromArray(): types, nested Data and collections. - The new object is built through the constructor, so readonly properties (PHP 8.1+) work.
- Nested objects are copied by reference;
with()is not a deep clone.
with() copies each constructor parameter from the property of the same name. When a parameter has no such property, with() throws a LogicException. Variadic constructor parameters are not supported by any hydration method.
#Data Attributes
Three attributes, in Pharaonic\Laravel\Architecture\Attributes, adjust how a Data object is hydrated and serialized. Put them on promoted constructor parameters, or on a property and its constructor parameter.
#MapName
MapName gives a field a different external name, used both to read input and to write output.
1use Pharaonic\Laravel\Architecture\Attributes\MapName; 2use Pharaonic\Laravel\Architecture\Data; 3 4class CustomerData extends Data 5{ 6 public function __construct( 7 #[MapName('first_name')] 8 public string $firstName, 9 ) {}10}11 12$customer = CustomerData::fromArray(['first_name' => 'Ahmed']);13 14$customer->firstName; // "Ahmed"15$customer->toArray(); // ['first_name' => 'Ahmed']- There is no automatic case conversion: fields without
MapNamekeep their PHP name. - Input is read by the external name only;
['firstName' => ...]does not match. with()uses PHP names:$customer->with(['firstName' => 'Mohamed']).- Two fields mapped to the same name, or different names declared on a property and its parameter, throw a
LogicException.
#Hidden
Hidden leaves a field out of toArray(), toJson() and jsonSerialize(), including when the object is nested inside another one.
1use Pharaonic\Laravel\Architecture\Attributes\Hidden; 2 3class AccountData extends Data 4{ 5 public function __construct( 6 public string $email, 7 #[Hidden] 8 public string $apiToken, 9 ) {}10}11 12$account->apiToken; // still readable13$account->toArray(); // ['email' => '...']Hidden does not affect hydration, property access or with().
Hidden only changes serialization. It does not encrypt the value or stop code, var_dump() or logs from reading it.
#DataCollection
DataCollection names the Data class of each element of an array or Illuminate\Support\Collection field.
1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class OrderItemData extends Data 6{ 7 public function __construct( 8 public string $sku, 9 public int $quantity = 1,10 ) {}11} 1use Illuminate\Support\Collection; 2use Pharaonic\Laravel\Architecture\Attributes\DataCollection; 3use Pharaonic\Laravel\Architecture\Data; 4 5class OrderData extends Data 6{ 7 public function __construct( 8 #[DataCollection(OrderItemData::class)] 9 public array $items,10 #[DataCollection(OrderItemData::class)]11 public ?Collection $gifts = null,12 ) {}13}14 15$order = OrderData::fromArray([16 'items' => [17 ['sku' => 'A-1', 'quantity' => 2],18 ['sku' => 'B-7'],19 ],20]);21 22$order->items[0]; // OrderItemData- Each element is built from an array with
fromArray(), or kept when it is already an instance of the class. - The field gets the type it declares: an
array, or a newCollection. Either one is accepted as input. - Keys are preserved, and an empty list is valid. A nullable field accepts
null. - Any other element, such as a string or another Data class, throws a
TypeErrorthat names the field and key. toArray()converts every element back to an array, keeping the keys.
A DataCollection that names a class that is not a concrete Data class, or that sits on a field whose type is not array or Collection, throws a LogicException the first time the class is used. There is no inference from PHPDoc: declare the attribute whenever a list holds Data objects.
#Contexts
A Context holds mutable state for one operation and is passed explicitly between the components that share it, typically the Tasks of a pipeline.
1namespace App\Contexts; 2 3use App\Order; 4use App\User; 5use Pharaonic\Laravel\Architecture\Context; 6 7class OrderContext extends Context 8{ 9 public float $total = 0;10 public ?string $coupon = null;11 public ?Order $order = null;12 13 /**14 * @param array<int, array{sku: string, price: float, quantity: int}> $items15 */16 public function __construct(public User $user, public array $items = []) {}17}#Sharing It Through a Pipeline
Each pipeline Task reads what the previous ones wrote and adds its own part.
1namespace App\Tasks; 2 3use App\Contexts\OrderContext; 4use Closure; 5use Pharaonic\Laravel\Architecture\Task; 6 7class CalculateTotalTask extends Task 8{ 9 public function handle(mixed $payload, Closure $next): mixed10 {11 /** @var OrderContext $payload */12 $payload->total = collect($payload->items)->sum(fn ($item) => $item['price'] * $item['quantity']);13 14 return $next($payload);15 }16} 1namespace App\Tasks; 2 3use App\Contexts\OrderContext; 4use App\Product; 5use Closure; 6use Pharaonic\Laravel\Architecture\Task; 7use RuntimeException; 8 9class ReserveStockTask extends Task10{11 public function handle(mixed $payload, Closure $next): mixed12 {13 /** @var OrderContext $payload */14 foreach ($payload->items as $item) {15 $reserved = Product::where('sku', $item['sku'])16 ->where('stock', '>=', $item['quantity'])17 ->decrement('stock', $item['quantity']);18 19 if ($reserved === 0) {20 throw new RuntimeException("{$item['sku']} is out of stock.");21 }22 }23 24 return $next($payload);25 }26} 1namespace App\Tasks; 2 3use App\Contexts\OrderContext; 4use App\Order; 5use Closure; 6use Pharaonic\Laravel\Architecture\Task; 7 8class CreateOrderTask extends Task 9{10 public function handle(mixed $payload, Closure $next): mixed11 {12 /** @var OrderContext $payload */13 $payload->order = Order::create([14 'user_id' => $payload->user->id,15 'total' => $payload->total,16 'coupon' => $payload->coupon,17 ]);18 19 $payload->order->items()->createMany($payload->items);20 21 return $next($payload);22 }23}The PlaceOrderAction runs them in order inside a transaction:
1$context = new OrderContext($request->user(), $request->input('items'));2 3$order = PlaceOrderAction::make()->handle($context);4 5$context->total; // set by CalculateTotalTask6$context->order; // set by CreateOrderTask, the same Order returned#What a Context Is Not
Context is an empty abstract class. It is not a Data object, and it intentionally offers nothing more:
- no
make(): create it withnewand your own constructor; - no hydration, serialization, magic accessors or key-value storage: declare typed properties;
- no container binding and no automatic propagation: pass it where it is needed.
Create a new Context for every independent operation. Sharing one instance across requests or queued jobs turns it into global state.
#Generators
Five Artisan commands write a new class from a stub.
| Command | Default folder | Suffix | Class |
|---|---|---|---|
make:action |
app/Actions |
Action |
extends Action, with an empty handle(): void |
make:task |
app/Tasks |
Task |
extends Task, with an empty handle(): void |
make:task --pipeline |
app/Tasks |
Task |
extends Task, with handle(mixed $payload, Closure $next): mixed |
make:service |
app/Services/Business |
Service |
extends Service, empty body |
make:data |
app/Data |
Data |
extends Data, with an empty constructor |
make:context |
app/Contexts |
Context |
extends Context, empty body |
#Names
php artisan make:action CreateOrder # app/Actions/CreateOrderAction.phpphp artisan make:action CreateOrderAction # the same file: the suffix is not doubledphp artisan make:action Orders/CreateOrder # app/Actions/Orders/CreateOrderAction.phpphp artisan make:task CalculateTotal --pipelineThe suffix is added only when the name does not already end with it (case-sensitive). Every segment must be a valid PHP class name. A name that is only the suffix, such as Action, is refused because the class would clash with its base class.
#Service Categories
php artisan make:service Pricing # app/Services/Businessphp artisan make:service Pricing --business # app/Services/Businessphp artisan make:service Stripe --integration # app/Services/Integrationphp artisan make:service Orders --boundary # app/Services/Boundary--business, --integration and --boundary are mutually exclusive.
#Custom Paths
--path writes into another folder, relative to the project root or absolute. It overrides the default folder, including a service category's.
php artisan make:action CreateOrder --path=modules/Orders/Actionsphp artisan make:service Orders --boundary --path=modules/Orders/ServicesThe namespace always comes from the autoload.psr-4 section of your composer.json: the longest mapped folder that contains the destination, plus the remaining folders. Nothing assumes App, so an application mapped as "Acme\\": "app/" gets Acme\Actions.
1"autoload": {2 "psr-4": {3 "App\\": "app/",4 "Modules\\": "modules/"5 }6}With this mapping, --path=modules/Orders/Actions gives Modules\Orders\Actions\CreateOrderAction. The command refuses, and writes nothing, when no mapping contains the folder, when two prefixes map the same folder, or when a folder name is not a valid namespace segment such as my-orders. Run composer dump-autoload after adding a mapping.
#Overwriting
An existing file is never replaced unless you pass --force.
php artisan make:data Order --force#Customizing the Stubs
Publish the stubs to change what every generated class looks like:
php artisan vendor:publish --tag=architecture-stubsThe files are copied to stubs/architecture: action.stub, task.stub, task.pipeline.stub, service.stub, data.stub and context.stub. Each one uses the {{ namespace }} and {{ class }} tokens. A stub you delete falls back to the package's version. The pharaonic, laravel-architecture and pharaonic-stubs tags publish the same files.
Laravel itself has no make:action, make:task, make:service, make:data or make:context. If another package registers one of these names after this package, Artisan uses the one registered last.
Every command exits with 0 when the file is written and 1 when it refuses.
#API Reference
All classes are in the Pharaonic\Laravel\Architecture namespace.
#Action
| Method | Description | Returns |
|---|---|---|
static make(array $parameters = []) |
Resolves the class through the container; $parameters overrides constructor parameters by name |
static |
__invoke(mixed ...$arguments) |
Calls your handle() with the same positional and named arguments |
mixed (null for a void handler) |
protected tasks(mixed $payload, array $tasks) |
Sends $payload through Laravel's pipeline |
mixed, what the pipeline returns |
#Task
| Method | Description | Returns |
|---|---|---|
static make(array $parameters = []) |
Resolves the class through the container | static |
__invoke(mixed ...$arguments) |
Calls your handle() |
mixed |
#Service
| Method | Description | Returns |
|---|---|---|
static make(array $parameters = []) |
Resolves the class through the container | static |
#Data
Implements Illuminate\Contracts\Support\Arrayable, Illuminate\Contracts\Support\Jsonable and JsonSerializable.
| Method | Description | Returns |
|---|---|---|
static fromArray(array $data) |
Builds the object through its constructor from an associative array | static |
static fromRequest(Request $request) |
validated() of a FormRequest, all() of any other request, then fromArray() |
static |
static fromModel(Model $model) |
fromArray($model->toArray()) |
static |
toArray() |
Initialized public properties by external name, without hidden ones, converted recursively | array |
toJson($options = 0) |
JSON of toArray() with your json_encode options |
string |
jsonSerialize() |
Same as toArray() |
array |
with(array $attributes) |
A new instance with the given fields, by PHP name, replaced | static |
#Attributes
| Attribute | Target | Effect |
|---|---|---|
Attributes\MapName(string $name) |
Property or constructor parameter | External name for hydration and serialization |
Attributes\Hidden |
Property or constructor parameter | Left out of toArray(), toJson() and jsonSerialize() |
Attributes\DataCollection(string $class) |
array or Collection property or parameter |
Builds each element as $class |
#Context
An empty abstract class with no methods.
#Exceptions
The package uses PHP's own exceptions; it defines none.
| Exception | Thrown when |
|---|---|
BadMethodCallException |
An Action or Task is invoked without a handle() method |
InvalidArgumentException |
fromArray() misses a required field; with() gets a key that is not a constructor parameter |
TypeError |
A value does not match its declared type, or a DataCollection element is not an array or an instance of its class |
LogicException |
A Data class declares duplicate or conflicting MapNames, an empty MapName, an invalid DataCollection, or a variadic constructor; with() cannot copy a parameter; a Data object contains itself |
JsonException |
toJson() cannot encode the data |
#Commands
| Command | Arguments and options |
|---|---|
make:action |
{name} --path= --force |
make:task |
{name} --path= --force --pipeline |
make:service |
{name} --path= --force --business --integration --boundary |
make:data |
{name} --path= --force |
make:context |
{name} --path= --force |
#Publish Tags
| Tag | Publishes |
|---|---|
architecture-stubs |
The generator stubs to stubs/architecture |
pharaonic-stubs, laravel-architecture, pharaonic |
The same files |
#Examples
#1. Controller, FormRequest, Data and Action
The request validates the input, the Data objects type it, and the Action does the work.
1namespace App\Http\Requests; 2 3use Illuminate\Foundation\Http\FormRequest; 4 5class StoreOrderRequest extends FormRequest 6{ 7 public function rules() 8 { 9 return [10 'items' => 'required|array|min:1',11 'items.*.sku' => 'required|string',12 'items.*.quantity' => 'required|integer|min:1',13 'coupon' => 'nullable|string',14 ];15 }16} 1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Data; 4 5class OrderItemData extends Data 6{ 7 public function __construct( 8 public string $sku, 9 public int $quantity = 1,10 ) {}11} 1namespace App\Data; 2 3use Pharaonic\Laravel\Architecture\Attributes\DataCollection; 4use Pharaonic\Laravel\Architecture\Data; 5 6class OrderData extends Data 7{ 8 public function __construct( 9 #[DataCollection(OrderItemData::class)]10 public array $items,11 public ?string $coupon = null,12 ) {}13} 1namespace App\Actions; 2 3use App\Data\OrderData; 4use App\Order; 5use Illuminate\Support\Facades\DB; 6use Pharaonic\Laravel\Architecture\Action; 7 8class CreateOrderAction extends Action 9{10 public function handle(OrderData $data, int $userId): Order11 {12 return DB::transaction(function () use ($data, $userId) {13 $order = Order::create(['user_id' => $userId, 'coupon' => $data->coupon]);14 15 foreach ($data->items as $item) {16 $order->items()->create($item->toArray());17 }18 19 return $order;20 });21 }22} 1namespace App\Http\Controllers; 2 3use App\Actions\CreateOrderAction; 4use App\Data\OrderData; 5use App\Http\Requests\StoreOrderRequest; 6 7class OrderController extends Controller 8{ 9 public function store(StoreOrderRequest $request, CreateOrderAction $createOrder)10 {11 $order = $createOrder(OrderData::fromRequest($request), $request->user()->id);12 13 return redirect()->route('orders.show', $order);14 }15}#2. A Checkout Pipeline With a Coupon Step
Add a step to the order pipeline from Contexts without touching the other Tasks.
1namespace App\Tasks; 2 3use App\Contexts\OrderContext; 4use Closure; 5use Pharaonic\Laravel\Architecture\Task; 6 7class ApplyCouponTask extends Task 8{ 9 public function handle(mixed $payload, Closure $next, string $code = 'WELCOME10', string $percent = '10'): mixed10 {11 /** @var OrderContext $payload */12 if ($payload->coupon === $code) {13 $payload->total = round($payload->total * (1 - (int) $percent / 100), 2);14 }15 16 return $next($payload);17 }18} 1namespace App\Actions; 2 3use App\Contexts\OrderContext; 4use App\Order; 5use App\Tasks\ApplyCouponTask; 6use App\Tasks\CalculateTotalTask; 7use App\Tasks\CreateOrderTask; 8use App\Tasks\ReserveStockTask; 9use Illuminate\Support\Facades\DB;10use Pharaonic\Laravel\Architecture\Action;11 12class CheckoutAction extends Action13{14 public function handle(OrderContext $context): Order15 {16 return DB::transaction(function () use ($context) {17 return $this->tasks($context, [18 CalculateTotalTask::class,19 ApplyCouponTask::class.':SUMMER20,20',20 ReserveStockTask::class,21 CreateOrderTask::class,22 ])->order;23 });24 }25} 1namespace App\Http\Controllers; 2 3use App\Actions\CheckoutAction; 4use App\Contexts\OrderContext; 5use Illuminate\Http\Request; 6 7class CheckoutController extends Controller 8{ 9 public function store(Request $request, CheckoutAction $checkout)10 {11 $context = new OrderContext($request->user(), $request->validate([12 'items' => 'required|array|min:1',13 'items.*.sku' => 'required|string',14 'items.*.price' => 'required|numeric',15 'items.*.quantity' => 'required|integer|min:1',16 ])['items']);17 $context->coupon = $request->input('coupon');18 19 return redirect()->route('orders.show', $checkout($context));20 }21}The :SUMMER20,20 suffix passes 'SUMMER20' and '20' to the Task after $next, as Laravel's pipeline does for middleware parameters.
#3. An Action From a Queued Job
Jobs stay thin: they hold the input and call the Action.
1namespace App\Actions; 2 3use App\Order; 4use Illuminate\Support\Facades\Mail; 5use Pharaonic\Laravel\Architecture\Action; 6 7class SendInvoiceAction extends Action 8{ 9 public function handle(Order $order): void10 {11 Mail::raw("Your order #{$order->id} totals {$order->total}.", function ($message) use ($order) {12 $message->to($order->user->email)->subject("Invoice #{$order->id}");13 });14 15 $order->update(['invoiced_at' => now()]);16 }17} 1namespace App\Jobs; 2 3use App\Actions\SendInvoiceAction; 4use App\Order; 5use Illuminate\Bus\Queueable; 6use Illuminate\Contracts\Queue\ShouldQueue; 7use Illuminate\Queue\SerializesModels; 8 9class SendInvoice implements ShouldQueue10{11 use Queueable, SerializesModels;12 13 public function __construct(public Order $order) {}14 15 public function handle(SendInvoiceAction $sendInvoice)16 {17 $sendInvoice($this->order);18 }19}The same Action works from a console command or a listener; nothing in it depends on where it is called from.
#4. A Boundary Service in Front of a Module
Other modules reach billing through BillingService only. Behind it, an Action uses the StripeGatewayService integration from Services.
1namespace Modules\Billing\Services; 2 3use Modules\Billing\Actions\ChargeCustomerAction; 4use Pharaonic\Laravel\Architecture\Service; 5 6class BillingService extends Service 7{ 8 public function __construct(protected ChargeCustomerAction $charge) {} 9 10 public function charge(int $userId, int $amountInCents): string11 {12 return $this->charge->handle($userId, $amountInCents);13 }14} 1namespace Modules\Billing\Actions; 2 3use App\Services\Integration\StripeGatewayService; 4use App\User; 5use Pharaonic\Laravel\Architecture\Action; 6 7class ChargeCustomerAction extends Action 8{ 9 public function __construct(protected StripeGatewayService $stripe) {}10 11 public function handle(int $userId, int $amountInCents): string12 {13 $user = User::findOrFail($userId);14 15 return $this->stripe->charge($user->stripe_id, $amountInCents);16 }17}php artisan make:service Billing --boundary --path=modules/Billing/Servicesphp artisan make:action ChargeCustomer --path=modules/Billing/ActionsBoth commands need "Modules\\": "modules/" in the autoload.psr-4 section of composer.json.
#5. Testing With Laravel's Mocks
make() and constructor injection both resolve through the container, so Laravel's usual mocking works without a package-specific API. This test charges a customer through the boundary from example 4 without calling Stripe.
1namespace Tests\Feature; 2 3use App\Services\Integration\StripeGatewayService; 4use App\User; 5use Illuminate\Foundation\Testing\RefreshDatabase; 6use Modules\Billing\Services\BillingService; 7use Tests\TestCase; 8 9class BillingTest extends TestCase10{11 use RefreshDatabase;12 13 public function test_it_charges_the_customer_through_stripe()14 {15 $user = factory(User::class)->create(['stripe_id' => 'cus_123']);16 17 $this->mock(StripeGatewayService::class, function ($mock) {18 $mock->shouldReceive('charge')->once()->with('cus_123', 5000)->andReturn('ch_123');19 });20 21 $this->assertSame('ch_123', BillingService::make()->charge($user->id, 5000));22 }23}#Troubleshooting
#"The field [x] is required to create [...]"
fromArray() did not find a key for a constructor parameter that has no default. A nullable type does not make a field optional. Give the parameter a default (public ?string $nickname = null) or include the key. When the field uses MapName, the message shows the external name first: send that key.
#TypeError when building a Data object
Values are not coerced. A form field "2" does not fit an int parameter. Cast the value before building the object, or validate and convert it in your FormRequest.
#A mapped field stays empty
Input is matched by the MapName name only. ['firstName' => ...] does not fill a field mapped to first_name. In with(), it is the other way around: use the PHP name.
#"[...] has no constructor parameter [...]" from with()
with() takes PHP property names and rejects unknown keys. Check for a typo or a MapName name.
#"[...] maps the fields [a] and [b] to the same name [b]"
Two fields would read and write the same key. Change one of the MapName values.
#"No autoload.psr-4 path of composer.json contains [...]"
The generator cannot tell the namespace of the destination folder. Add a PSR-4 mapping for it in composer.json, run composer dump-autoload, and run the command again.
#"[...] already exists. Use --force to overwrite it."
Generators never replace a file silently. Pass --force to overwrite it.
#My published stub is ignored
Published stubs must be in stubs/architecture at the project root, with the original file name, such as action.stub. A stub that is missing from that folder falls back to the package's.
#A pipeline stops early
A pipe that returns without calling $next($payload) ends the pipeline, and its return value becomes the result. Make sure every pipeline Task returns $next($payload).
#make:action runs another package's command
Another package registered the same command name after this one. Artisan keeps the last registration. Check php artisan list make and the order of your service providers.
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Architecture!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .