您现在的位置是:首页 >PHP网站首页PHP
Laravel/Lumen 自动注入依赖composer包
- 学无止境
- 2023-09-20
- 5461 已阅读
- 0
简介Laravel/Lumen 自动注入依赖 注解composer包 #PHP8
composer require yanghui/php-annotations "@dev"
laravel: 在配置文件config/app.php providers 加上
Alex\Annotations\Providers\AnnotationServiceProvider::class
lumen:在bootstrap/app.php 加上
$app->register(Alex\Annotations\Providers\AnnotationServiceProvider::class);
1、Autowired 自动注入
<?php
namespace App\Services\Api;
use Alex\Annotations\Services\Autowired;
use App\Models\IntegralGoods;
class IntegralGoodsService extends BaseService
{
#[Autowired]
protected IntegralGoods $integralGoods;
public function list()
{
return $this->integralGoods
->where(['status' => 1])
->select(['id', 'name', 'image', 'spec', 'integral', 'price', 'stock'])
->orderBy('sort')
->pager();
}
}
2、#[Config] 读取配置
<?php
namespace App\Components;
use Alex\Annotations\Services\Config;
class JWT
{
#[Config('auth.jwt.header')]
protected $header;
#[Config('auth.jwt.secret')]
protected $secret;
#[Config('auth.jwt.algConfig')]
protected $algConfig;
}
3、#[Validated] 自动验证
<?php
namespace App\Requests\Admin;
use Alex\Annotations\Services\Validate\Exists;
use Alex\Annotations\Services\Validate\In;
use Alex\Annotations\Services\Validate\Required;
use Alex\Annotations\Services\Validate\RequiredIf;
use Alex\Annotations\Services\Validate\Validated;
use Alex\Annotations\Services\Validate\Custom;
use App\Requests\Api\Custom\IsPhone;
use App\Requests\Api\Custom\VerifyCaptcha;
use App\Requests\Request;
#[Validated]
class LoginRequest extends Request
{
#[RequiredIf(['type' => 0])]
#[Exists('system_users', '用户名不存在')]
protected string $username;
#[RequiredIf(['type' => 1])]
#[Custom(IsPhone::class)]
protected string $phone;
#[RequiredIf(['type' => 1])]
protected string $code;
#[RequiredIf(['type' => 0])]
protected string $password;
#[Required]
protected string $captchaKey;
#[Required]
#[Custom(VerifyCaptcha::class, '图形验证码不正确')]
protected string $captcha;
#[In([0, 1])]
protected int $type;
}
<?php
namespace App\Requests\Api\Custom;
use Alex\Annotations\Services\Validate\CustomInterface;
class IsPhone implements CustomInterface
{
public function handle()
{
return function($attribute, $value) {
return preg_match('/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0-8])|(18[0-9])|166|198|199|(147))\\d{8}$/', $value);
};
}
}
<?php
namespace App\Http\Controllers\Admin;
use Alex\Annotations\Services\Autowired;
use App\Components\Response;
use App\Http\Controllers\Controller;
use App\Requests\Admin\LoginRequest;
use App\Services\Admin\AuthService;
use Illuminate\Http\JsonResponse;
class AuthController extends Controller
{
#[Autowired]
protected AuthService $server;
public function login(LoginRequest $request)
{
return Response::success($this->server->login($request));
}
}