一、重写容器方法:
/config/container.php
<?php
declare(strict_types=1);
//use Hyperf\Di\Container;
use Core\Common\Dependencies\Di\Container;
use Hyperf\Di\Definition\DefinitionSourceFactory;
use Hyperf\Utils\ApplicationContext;
$container = new Container((new DefinitionSourceFactory(true))());
if (! $container instanceof \Psr\Container\ContainerInterface) {
throw new RuntimeException('The dependency injection container is invalid.');
}
return ApplicationContext::setContainer($container);二、重写
/app/Core/Common/Dependencies/Di/Container.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Core\Common\Dependencies\Di;
class Container extends \Hyperf\Di\Container
{
public function make(string $name, array $parameters = [])
{
$instance = parent::make($name, $parameters);
if ($instance instanceof InitializeInerface) {
$instance->initialize();
}
return $instance;
}
}三、实现重写的接口
/app/Core/Common/Dependencies/Di/Contract/InitializeInerface.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Core\Common\Dependencies\Di\Contract;
interface InitializeInerface
{
public function initialize(): void;
}四、在自动加载initialize()方法的类中实现此接口,即可
/app/Controller/Admin/AdminLogController.php
<?php
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Controller\BaseController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\LoginAuthMiddleware;
use App\Middleware\AdminAuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use App\Models\AdminLog;
use Core\Common\Dependencies\Di\Contract\InitializeInerface;
/**
* AdminLogController
* 后台日志控制器
*
* @package App\Controller\Admin
*
* @AutoController(prefix="admin/admin_log")
*
* @Middlewares({
* @Middleware(LoginAuthMiddleware::class),
* @Middleware(AdminAuthMiddleware::class)
* })
*/
class AdminLogController extends BaseController implements InitializeInerface
{
use \App\Traits\Admin\Controller\Expert;
/**
*
* @Inject()
* @var AdminLog
*/
private AdminLog $model;
/**
* 是否开启限制数据访问
*
* @var bool
*/
protected ? bool $limitData = null;
/**
* 限制数据的条件字段
*
* @var string
*/
protected string $LimitField = 'admin_id';
public function initialize(): void
{
if ($this->limitData === null) {
$this->limitData = in_array($this->LimitField, $this->model->getFillable());
}
}
}至此,就实现了hyperf的自动加载类的方法,如果需要其他方法,只需在第三和第四步中将方法实现并在实际的类中implements即可!
无论从事什么行业,只要做好两件事就够了,一个是你的专业、一个是你的人品,专业决定了你的存在,人品决定了你的人脉,剩下的就是坚持,用善良專業和真诚赢取更多的信任。
游客:58.20.204.*:看不懂
2021-03-10 12:40:37 回复
游客:27.221.124.*:但是也觉得很厉害
2021-03-10 12:40:49 回复