Laravel: The hidden Pipeline [Part 3]

Serialized content processing, meet your new friend: the Pipeline.

Photo by Samuel Zeller on Unsplash

A Hub to rule them all

$hub = app(\Illuminate\Pipeline\Hub::class);$hub->defaults(function ($pipeline, $object) {
return $pipeline
->send($object)
->through([
EncodeToHtml::class
AddPunctutation::class,
RemoveDuplicatesCharacters::class,
UppercaseFirstCharacterOfEachPhrase::class,
])
->thenReturn();
});
$hub->pipeline('encode-only', function ($pipeline, $object) {
return $pipeline
->send($object)
->through(EncodeToHtml::class)
->thenReturn();
});
/**
* Updates an Article
*
* @param \Illuminate\Http\Request $request
* @param \App\Article $article
* @param \Illuminate\Pipeline\Hub $hub
* @return \Illuminate\Http\Response
*/
public function save(Request $request, Article $article, Hub $hub)
{
$request->validate([
'message' => 'required|string',
]);
$article->message = $hub->pipe($request->message); $article->save(); return response()
->view('article.saved')
->with('article', $article);
}

What about that Service Provider?

/**
* Register any application services.
*
*
@return void
*/
public function register()
{
$this->app->extend(
\Illuminate\Contracts\Pipeline\Hub::class,
function ($hub) {
$hub->defaults(function ($pipeline, $object) {
return $pipeline
->send($object)
->through(\App\Pipelines\EncodeToHtml::class)
->thenReturn();
});

return $hub;
}
)
}
/**
* Register any application services.
*
*
@return void
*/
public function register()
{
$this->app->singleton(\App\Hubs\ArticleHub::class);
$this->app->singleton(\App\Hubs\CommentHub::class);
}
/**
* Updates an Article
*
* @param \Illuminate\Http\Request $request
* @param \App\Article $article
* @param \App\Hubs\ArticleHub $hub
* @return \Illuminate\Http\Response
*/
public function save(Request $request,
Article $article,
ArticleHub $hub)
{
$request->validate([
'message' => 'required|string',
'excerpt' => 'required|string|max:255'
]);
$article->message = $hub->pipe($request->message, 'body');
$article->excerpt = $hub->pipe($request->excerpt, 'excerpt');
$article->save(); return response()
->view('article.saved')
->with('article', $article);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com