hyperf 如何实现 Tp 里面的 common 自定义函数
本次采用中间件的方式实现
1.先自定义一个中间件放在Middleware目录下面
<?php declare(strict_types=1); namespace App\Middleware; use Hyperf\Context\Context; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; class FunctionMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { # 配置自定义函数 $helpersPath = BASE_PATH; foreach (glob("$helpersPath/app/Helper/common/*.php") as $file) { require_once $file; } return $handler->handle($request); } }
2.在config/autoload/middlewares.php 里面添加
\App\Middleware\FunctionMiddleware::class,
3.创建 /app/Helper/common 文件夹,当然你可以自己写任何路径,记得和第一步里面的配置路劲对应就行
4.在common文件夹下面创建.php文件,文件名不限制,文件里面和tp的common一样,直接写函数即可,如我创建了一个Function.php
<?php /** * # +======================================================================== * # | - @name 数据打印 * # | - @author csh <just_leaf@foxmail.com> * # | - @copyright 鈤励云模 - 乂安 * # +======================================================================== */ if (!function_exists('pf')) { function pf($array) { header("Content-type:text/html;charset=utf-8"); print_r($array); } }
5.随便在任何地方直接使用pf()函数即可

浙公网安备 33010602011771号