PHP code example of longaodai / repository-pattern
1. Go to this page and download the library: Download longaodai/repository-pattern 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/ */
longaodai / repository-pattern example snippets
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
\LongAoDai\Repositories\RepositoryServiceProvider::class,
])->toArray(),
Copying file [vendor/longaodai/repository-pattern/config/pattern.php] to [config/pattern.php] ............................................... DONE
Repository Comment created successfully !!!
Implement: App\Repositories\CommentEloquentRepository.php
Interface: App\Repositories\CommentRepositoryInterface.php
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
\LongAoDai\Repositories\RepositoryServiceProvider::class,
\App\Providers\RepositoryServiceProvider::class,
])->toArray(),
use LongAoDai\Repositories\BaseRepository;
class UserRepository extends BaseRepository
{
/**
* Specify the model class name.
*
* @return mixed
*/
public function model()
{
return User::class;
}
}
public function getList($data = null, $options = null): mixed
{
$this->method('select', [
'name', 'email'
]);
return parent::getList($data, $options);
}
protected function filter($params): UserRepository
{
if ($params->get('name')) {
$this->method('where', 'name', 'like', '%' . $params->get('name') . '%');
}
if ($params->get('id')) {
$this->method('where', 'id', $params->get('id'));
}
return parent::filter($params);
}
protected function mark($params): UserRepository
{
if ($params->option('id')) {
$this->method('where', 'id', $params->option('id'));
}
return parent::mark($params);
}
public function index()
{
$repository = app(UserRepository::class);
// Get list with pagination
$user = $repository->getList($data = null, $options = null);
// Get all data
$user = $repository->all($data = null, $options = null);
// Find by id
$user = $repository->find(['id' => 1]);
// Update data
$user = $repository->update(
collect([
'name' => 'Vo Chi Long'
]),
collect(['id' => 1])
);
// Create data
$user = $repository->create(collect([
'name' => 'Vo Chi Long',
'email' => '[email protected]',
'password' => bcrypt('password'),
]));
// Get first by params condition
$user = $repository->first(collect([
'name' => 'Long'
]));
// Update or Create by options condition
$user = $repository->updateOrCreate(collect([
'name' => 'Vo Chi Long'
]), collect([
'email' => '[email protected]'
]));
// Delete data by condition
$user = $repository->destroy(['id' => 10]);
return json_encode($user ?? []);
}