打开终端,执行以下命令初始化项目:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
声明接口业务类 appservicesUserService
namespace app\services;
interface UserService
{
public function show($id);
public function all();
}
接口实现文件 appservicesimplUserServiceImpl
namespace app\services\impl;
use app\services\UserService;
class UserServiceImpl implements UserService
{
private $users = [
['id' => 1, 'name' => 'xialei'],
['id' => 2, 'name' => 'zhangsan'],
];
public function show($id)
{
foreach ($this->users as $user) {
if ($user['id'] == $id) {
return $user;
}
}
return null;
}
public function all()
{
return $this->users;
}
}
注册依赖关系 config/web.php
use app\services\UserService;
use app\services\impl\UserServiceImpl;
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'container' => [
'definitions' => [
UserService::class => UserServiceImpl::class
]
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '0xGrStOOZE2oXxNNiu-o2eYovJ_Ia1Dk',
],
'response' => [
'format' => 'json'
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
添加控制器 appcontrollersUserController
namespace app\controllers;
use app\services\UserService;
use yii\base\Module;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class UserController extends Controller
{
private $userService;
public function __construct(string $id, Module $module, UserService $userService, array $config = [])
{
$this->userService = $userService;
parent::__construct($id, $module, $config);
}
public function actionShow($id)
{
$user = $this->userService->show($id);
if (empty($user)) {
throw new NotFoundHttpException('用户不存在');
}
return $user;
}
public function actionAll()
{
return $this->userService->all();
}
}
运行测试服务器
./yii serve/index
[{
"id": 1,
"name": "xialei"
}, {
"id": 2,
"name": "zhangsan"
}]
{
"id": 1,
"name": "xialei"
}