Skip to content

Commit d2307f8

Browse files
authored
readme
1 parent 38b8eb3 commit d2307f8

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

README.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ In .env file type your database credentials in these lines:
6161
DB_DATABASE=laravel
6262
DB_USERNAME=root
6363
DB_PASSWORD=
64+
6465
After that, run these commands from terminal:
6566

6667
composer install
@@ -153,7 +154,34 @@ Also, you get really independent on Eloquent, as you don't use generic Eloquent
153154

154155
<a id="Decorators"></a>
155156
## Decorators
156-
//TODO
157+
158+
Decorators are really great, as they allow you to extend an object's behaviour in a really OOP way. What would you do if you nedded to log the value of your action, e.g. list of books? Well, we often see this recommendation:
159+
160+
public function execute(PaginateRequestInterface $paginateRequest): BookCollection
161+
{
162+
$bookCollection = [];
163+
// some code here
164+
165+
Log::info('get ' . count($bookCollection) . 'books');
166+
167+
return new BookCollection(...$bookCollection);
168+
}
169+
170+
But what did we do right now? We broke here open closed principle. Our code must be open for extension, but closed for modification. By inserting Log::info() to execute() method, we modified it, instead of extending. Also, our object now does more than one thing: it fectches books and logs the result.
171+
172+
How can we do it in a OOP way? Decorators to the rescue!
173+
In a Laravel service container we decorate our action before binding it to our interface:
174+
175+
public function register()
176+
{
177+
$bookListAction = new GetBookListAction(new BookEloquentProxy());
178+
$bookListActionLogged = new GetBookListActionLogger($bookListAction);
179+
180+
$this->app->bind(GetBookListActionInterface::class, function ($app) use($bookListActionLogged) {
181+
return $bookListActionLogged;
182+
});
183+
}
184+
As GetBookListActionLogger implements GetBookListActionInterface, it can be easily bound to this in a service container and in this case we extended GetBookListAction instead of modifying it. We can add as many deorators as we like and everything will work fine.
157185

158186
<a id="API-Resources"></a>
159187
## API resources

0 commit comments

Comments
 (0)