1. Go to this page and download the library: Download phpno1/architecture 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/ */
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\UserService;
use App\Http\Responses\User\IndexResponse;
class UserController extends Controller
{
private $user;
public function __construct(UserService $userService)
{
$this->user=$userService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$result=$this->user->getUsers();//这里调用是业务层资源方法
return new IndexResponse($result);
}
namespace App\Http\Responses\User;
use Illuminate\Contracts\Support\Responsable;
use App\Traits\ResponseTrait;
class UserIndexResponse implements Responsable
{
use ResponseTrait;
protected $result;
public function __construct($result)
{
$this->result = $result;
}
public function toResponse($request)
{
$data = $this->transform();
return $data;
}
protected function transform()
{
//分页数据例子
$this->result->getCollection()->transform(function ($user) {
return [
'id' => $user->id,
'name' => $user->name,
];
});
//集合数据例子
$this->result->transform(function ($user) {
return [
'id' => $user->id,
'name' => $user->name,
];
});
return $this->result;
}
}
// 获取所有记录
$this->repository->all();
// 根据id查询单条记录
$this->repository->find(int $id);
// 获取第一条记录
$this->repository->first();
// 获取总记录数
$this->repository->count();
// 根据一个或多个 AND WHERE 条件查询。得到一个结果集
// 单个条件写法:->findWhere('name', 'tome');
// 多个条件写法:->findWhere(['name', 'tome'], ['age', '>', 20]);
$this->repository->findWhere(...$condition);
// 根据一个或多个 AND WHERE 条件查询。得到一条记录。
$this->repository->findWhereFirst(...$condition);
// 根据一个或多个 AND WHERE 条件获取记录数
$this->repository->findWhereCount(...$condition);
//模型中定义
class User extends Model
{
public function scopeUserFields()
{
return $this->select(['id','name','email']);
}
}
//仓库中调用
class UserRepositoryEloquent extends AbstractRepository implements UserRepository
{
public function getUsers(int $perPage=0)
{
return $this->userFields()->withCriteria(
new FilterRequest($this->filters)
)->paginate($perPage);
}
}
//当Repository提供的method无法满足业务
public function do()
{
// 使用toEntity() 转换回Model或Build对象
return $this->repository
->toEntity()
->where(...)
->orWhere(...)
->when(...)
->get(...);
}
public function getUserList()
{
// 参数1:缓存的key值
// 缓存中有数据则从缓存中取,没有数据则从数据库取一次放入缓存。
$this->getOrCache('getUserList', function () {
return $this->paginate();
});
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.