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 );
	}
}

$user = app( UserRepository::class )->create([
	'firstname' => 'Krazy',
	'lastname'  => 'Danny',
	'email'	    => '[email protected]',
	'active'    => true,
]);

$user_id = $user->getKey();


$user = app( UserRepository::class )->get( $user_id );


$user->active = false;

app( UserRepository::class )->save( $user );


app( UserRepository::class )->delete( $user );


$q = User::where( 'active', true );

$userCollection = app( UserRepository::class )->find( $q );


$q = User::where( 'active', true );

$user = app( UserRepository::class )->first( $q );


$q = User::where( 'active', true );

$userCount = app( UserRepository::class )->count( $q );


$q = User::where( 'active', true );

app( UserRepository::class )->remember()->during( 3600 )->find( $q );


app( UserRepository::class )->remember( $user )->during( 3600 );


app( ReservationsRepository::class )->remember( $reservation )->according( 'expiresIn' );


$q = User::where( 'active', true );

app( UserRepository::class )->rememberForever()->find( $q );


app( UserRepository::class )->rememberForever( $user );


$q = User::where( 'active', true );

app( UserRepository::class )->fromCache()->find( $q );


app( UserRepository::class )->fromCache( $user );


$query = User::where( 'active', true );

app( UserRepository::class )->forget( $query );


app( UserRepository::class )->forget( $userModelInstance );


app( UserRepository::class )->forget( $user_id );


$user->active = false;
$user->save();

$forgets = [];

#removes user model from cache
app( UserRepository::class )->forget( $user, $forgets );

#removes query that finds active users
$query = User::where( 'active', true );
app( UserRepository::class )->forget( $query, $forgets );

#requests all queued removals to the cache server
app( UserRepository::class )->forget( $forgets );


$user = app( UserRepository::class )->remember()->during( 3600 )->get( $user_id );


$q = User::where( 'active', true );

$userCollection = app( UserRepository::class )->remember()->during( 3600 )->find( $q );

$userCount = app( UserRepository::class )->remember()->during( 3600 )->count( $q );

$firstUser = app( UserRepository::class )->remember()->during( 3600 )->first( $q );


$user = app( UserRepository::class )->rememberForever()->get( $user_id );


$q = User::where( 'active', true );

$userCollection = app( UserRepository::class )->rememberForever()->find( $q );

$userCount = app( UserRepository::class )->rememberForever()->count( $q );

$firstUser = app( UserRepository::class )->rememberForever()->first( $q );


# 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,
			])
		);
	}

}


$activeUsers = app( UserRepository::class )->findByState( 'active' );

$activeUsers = app( UserRepository::class )->remember()->during( 3600 )->findByState( 'active' );

$activeUsers = app( UserRepository::class )->rememberForever()->findByState( 'active' );


app( UserRepository::class )->forget( $user );


$user->active = false;
$user->save();

$query = User::where( 'active', true );
app( UserRepository::class )->forget( $query );


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
}


app( UserRepository::class )->rememberForever( $user );
// or
app( UserRepository::class )->remember( $user )->during( 3600 );


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
})


app( UserRepository::class )->silently()->rememberForever()->get( $user_id );


$model = SomeModel::create( $data );


$model = app( SomeModelRepository::class )->buffer( new SomeModel( $data ) );