PHP code example of imanghafoori / laravel-middlewarize
1. Go to this page and download the library: Download imanghafoori/laravel-middlewarize 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/ */
imanghafoori / laravel-middlewarize example snippets
// Normal Call:
$myObj->myMethod();
// Decorated Call:
$myObj
->middlewares([...])
->myMethod():
class UserRepository
{
use Middlewarable; // <---- Use "Middlewarable" trait on your class
public function find($id)
{
return User::find($id); // <---- we wanna cache it, right?
}
...
}
class CacheMiddleware
{
public function handle($data, $next, $key, $ttl)
{
// 1. This part runs before method call
if (Cache::has($key)) {
return Cache::get($key);
}
$value = $next($data); // <--- 2. Runs the actual method
Cache::put($key, $value, $ttl); // <-- 3. This part runs after method
return $value;
}
}
public function boot()
{
app()->singleton('cacher', CacheMiddleware::class); // <---- Optional step
}
public function show($id, UserRepository $repo)
{
$cachedUser = $repo
->middleware('cacher:fooKey,60')
->find($id);
}
public function show($id, UserRepository $repo)
{
if (Cache::has('user.'.$id)) {
return Cache::get('user.'.$id); // <--- extra fluff around ->find($id)
}
$value = $repo->find($id); // <--- important method call here.
Cache::put('user.'.$id, $value, 60); // <--- extra fluff around ->find($id)
return $value;
}
public function show($id, UserRepository $repo)
{
$cachedUser = $repo
->middleware('cacher@MyHandle1:fooKey,60') // <--- Overrides default "handle" method name
->find($id);
}
public function show($id, UserRepository $repo)
{
$cachedUser = $repo->middleware(['middle1', 'middle2', 'middle3'])->find($id);
}
$obj = new CacheMiddleware('myCacheKey', etc...); // <---- you send depedencies to it.
$repo->middleware($obj)->find($id);
User::find($id); // <--- Sample static method call
User::middlewared('cache:key,10')->find($id); // <--- you can have a decorated call
// also you must put 'middlewarable' trait on User model.
class NullCacheMiddleware
{
public function handle($data, $next, $key, $ttl)
{
return $next($data); // <--- this "null middleware" does nothing.
}
}
public function testSomeThing()
{
app()->singleton('cacher', NullCacheMiddleware::class); // <--- this causes to replace the cache middleware
$this->get('/home');
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.