hyperf: 为项目定义全局函数

一,修改composer.json

    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Functions.php"
        ]
    },

在files数组中增加我们的函数文件

二,源代码

app/Functions.php

<?php

use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

if (! function_exists('container')) {
    /**
     * 获取容器对象
     *
     * @param string $id
     * @return mixed|\Psr\Container\ContainerInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function container(string $id = ''): mixed
    {
        $container = ApplicationContext::getContainer();

        if ($id) return $container->get($id);

        return $container;
    }
}

if (! function_exists('request')) {
    /**
     * request 实例
     *
     * @return RequestInterface|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function request(): mixed
    {
        return container()->get(RequestInterface::class);
    }
}

if (! function_exists('response')) {
    /**
     * response 实例
     *
     * @return ResponseInterface|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function response(): mixed
    {
        return container()->get(ResponseInterface::class);
    }
}


if (! function_exists('get_client_ip')) {
    /**
     * 获取客户端 ip
     *
     * @return mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function get_client_ip(): string
    {
        $request = request();
        return $request->getHeaderLine('X-Forwarded-For')
            ?: $request->getHeaderLine('X-Real-IP')
                ?: ($request->getServerParams()['remote_addr'] ?? '')
                    ?: '127.0.0.1';
    }
}

调用函数

controller/ImageController.php

    public function imagedetail(RequestInterface $request, ResponseInterface $response) {

        $ip = get_client_ip();

        $data = [
            'ip' => $ip
        ];
        return $response->json($data);

    }

三,测试效果:

 

posted @ 2025-02-09 19:17  刘宏缔的架构森林  阅读(102)  评论(0)    收藏  举报