PHP code example of monospice / spicy-repositories
1. Go to this page and download the library: Download monospice/spicy-repositories 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/ */
use Monospice\SpicyRepositories\Laravel\EloquentRepositoryServiceProvider;
class RepositoryServiceProvider extends EloquentRepositoryServiceProvider
{
// repository binding methods here
}
class RepositoryServiceProvider extends EloquentRepositoryServiceProvider
{
protected function bindUserRepository()
{
$this->interface = \App\Repositories\Interfaces\UserRepository::class;
return \App\Repositories\UserRepository::class;
}
}
class RepositoryServiceProvider extends EloquentRepositoryServiceProvider
{
protected function bindUserRepository()
{
$this->interface = \App\Repositories\Interfaces\UserRepository::class;
return function () {
if ($someCondition) {
$model = new \App\User();
} else {
$model = new \App\AdminUser();
}
return new \App\Repositories\UserRepository($model);
};
}
}
use Monospice\SpicyRepositories\Interfaces\Repository;
use Monospice\SpicyRepositories\Interfaces\BasicCriteria;
interface UserRepositoryInterface extends Repository, BasicCriteria
{
// custom repository methods here
}
use Monospice\SpicyRepositories\Laravel\EloquentRepository;
use App\Repositories\UserRepositoryInterface;
class UserRepository extends EloquentRepository implements UserRepositoryInterface
{
public function __construct(User $user)
{
parent::__construct($user);
}
// custom repository methods here
}
class UserController extends Controller
{
public function __construct(UserRepositoryInterface $users)
{
// use the repository
$users->getAll();
}
}
$repository->updateOrCreate()
->where([
'first' => 'George',
'last' => 'Washington',
])
->set([
'occupation' => 'President of the US'
]);
$repository->updateOrCreate()
->where(['first' => 'George'])
->orWhere(['first' => 'Denzel'])
->set(['occupation' => 'Some guy named Washington']);
$recordId = 1;
$repository->delete($recordId);
$repository->getResult();
class UserRepository extends EloquentRepository implements UserRepositoryInterface
{
public function customGetAll()
{
return $this->orderBy('name')->getAll();
}
}
$repository->customGetAll(); // the custom method
$repository->getAll(); // a built-in method