PHP code example of krazydanny / laravel-repository
1. Go to this page and download the library: Download krazydanny/laravel-repository 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/ */
krazydanny / laravel-repository example snippets
namespace App\Repositories;
use App\User;
use KrazyDanny\Laravel\Repository\BaseRepository;
class UserRepository extends BaseRepository {
public function __construct ( ) {
parent::__construct(
User::class, // Model's full class name
'Users' // OPTIONAL the name of the cache prefix. The short class name will be used by default. In this case would be 'User'
);
}
}
namespace App\Providers;
use App\Repositories\UserRepository;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
public function register ( ) {
$this->app->singleton(
UserRepository::class,
function () {
return (new UserRepository);
}
);
}
# other service provider methods here
}
use App\Repositories\UserRepository;
$userRepository = app( UserRepository::class );
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\UserRepository;
class UserController extends Controller
{
public function myMethod( UserRepository $userRepository, $id){
// you can now use the repository to work with cached models
$user = $userRepository->get( $id );
}
}
# create a new user in cache and database
$user = app( UserRepository::class )->rememberForever()->create([
'firstname' => 'Krazy',
'lastname' => 'Danny',
'email' => '[email protected]',
'active' => true,
]);
# update an existing user in cache and database
$user->active = false;
app( UserRepository::class )->rememberForever()->save( $user );
# create a new user in cache and database
$user = app( UserRepository::class )->remember()->during( 3600 )->create([
'firstname' => 'Krazy',
'lastname' => 'Danny',
'email' => '[email protected]',
'active' => true,
]);
# update an existing user in cache and database
$user->active = false;
app( UserRepository::class )->remember()->during( 3600 )->save( $user );
$model = app( TransactionsRepository::class )->buffer( new Transactions( $data ) );
$model = app( TransactionsRepository::class )->index( new Transactions( $data ) );
app( TransactionsRepository::class )->persist(
// the first param is a callback which returns true if models were persisted successfully, false otherwise
function( $collection ) {
foreach ( $collection as $model ) {
// do database library custom and optimized logic here
// for example: you could use bulk inserts and transactions in order to improve both performance and consistency
}
if ( $result )
return true; // if true remove model ids from persist() queue
return false; // if false keeps model ids in persist() queue and tries again next time persist() method is called
},
// the second param (optional) is an array with one or many of the following available options
[
'written_since' => 0, // process only models written since ths specified timestamp in seconds
'written_until' => \time(), // process only models written until the given timestamp in seconds
'object_limit' => 500, // the object limit to be processed at the same time (to prevent memory overflows)
'clean_cache' => true, // if true and callback returns true, marks models as persisted
'method' => 'buffer' // buffer | index
]
);
namespace App\Repositories;
use App\User;
use KrazyDanny\Laravel\Repository\BaseRepository;
class UserRepository extends BaseRepository {
public function __construct ( ) {
parent::__construct(
User::class, // Model's class name
'Users' // the name of the cache prefix
);
}
public function findByState ( string $state ) {
return $this->find(
User::where([
'state' => $state,
'deleted_at' => null,
])
);
}
}
namespace App\Repositories;
use App\User;
use KrazyDanny\Laravel\Repository\BaseRepository;
class UserRepository extends BaseRepository {
public function __construct ( ) {
parent::__construct(
User::class, // Model's class name
'Users' // the name of the cache prefix
);
}
// then call this to invalidate active users cache and any other queries or models cache you need.
public function forgetOnUserSave ( User $user ) {
// let's use a queue to make only one request with all operations to the cache server
$invalidations = [];
// invalidates that specific user model cache
$this->forget( $user, $invalidations );
// invalidates the active users query cache
$this->forget(
User::where([
'state' => 'active',
'deleted_at' => null,
]),
$invalidations
);
// makes request to the server and invalidates all cache entries at once
$this->forget( $invalidations );
}
}
namespace App\Observers;
use App\User;
use App\Repositories\UserRepository;
class UserObserver {
public function saved ( User $model ) {
app( UserRepository::class )->forgetOnUserSave( $model );
}
# here other observer methods
}
namespace App\Observers;
use App\UserSettings;
use App\Repositories\UserRepository;
class UserSettingsObserver {
public function saved ( UserSettings $model ) {
app( UserRepository::class )->remember( $model )->during( 3600 );
}
# here other observer methods
}
$callback = function ( $cacheHit, $result ) {
if ( $cacheHit ) {
// do something when the query hits the cache
}
else {
// do something else when the query hits the database
// this is not for storing the model in cache, remember the repository did it for you.
}
}
app( UserRepository::class )->observe( $callback )->rememberForever()->get( $user_id );
$callback = function ( $cacheHit, $result ) {
if ( $cacheHit ) {
// do something when the query hits the cache
}
else {
// do something else when the query hits the database
// this is not for storing the model in cache, remember the repository did it for you.
}
}
app( UserRepository::class )->observeAlways( 'afterGet', $callback);
app( UserRepository::class )->rememberForever()->get( $user_A_id );
app( UserRepository::class )->rememberForever()->get( $user_B_id );
app( UserRepository::class )->handleCacheExceptions(function( $e ){
// here we can do something like log the exception silently
})
app( UserRepository::class )->handleDatabaseExceptions(function( $e ){
// here we can do something like log the exception silently
})