walkor / webman

Probably the fastest PHP web framework in the world.
https://webman.workerman.net/
MIT License
2.2k stars 216 forks source link

关于编写辅助类的一个问题 #268

Open HyMax opened 2 years ago

HyMax commented 2 years ago

引用第三方类库,是否需要改写为单例模式,因为是常驻内存的PHP,那每次 new 了之后也是开辟了相应的资源的,就不知道 new 多了会不会有问题。

walkor commented 2 years ago

不一定都需要单例。我们的编码都在函数里运行的,根据php的机制,函数里的变量包括创建的类在函数在没有外部引用的情况下使用完都会自动释放。

HyMax commented 2 years ago

好的,大佬,我还是问回之前 server.php 里面的 max_request 的问题:

  1. 进程达到 max_request 的次数之后是否还会接受新的请求,我看代码好像还会。(如果还会接受新的请求的话,也就是大概在低估,例如半夜的时候才有机会重启进程)
  2. 比如我开了 4 个进程,那这 4个进程是随机进行接受请求的,还是说根据内部计数器有一个均衡的调度的。
walkor commented 2 years ago

1、达到max_request还会接受请求。max_request主要是为了防止业务出现内存泄漏。除非是故意向全局静态数组不停的添加数据,否则很少会遇业务内存泄漏的情况。所以大部分业务不必担心max_request 相关问题。max_request 可能会在未来 webman v2.0去掉,改为用统一的监控进程监控并重启。 2、哪个进程空闲,哪个进程接受连接,然后这个连接的请求都由这个进程处理。

guanhui07 commented 1 year ago

HyMax

class Container
{
    /**
     * @var \DI\Container
     */
    public static $container;

    /**
     * @see https://php-di.org/doc/attributes.html
     * @return \DI\Container
     * @throws Exception
     */
    public static function instance(): \DI\Container
    {
        if (!self::$container) {
            $containerBuilder = new ContainerBuilder();
            // 通过以下方式ContainerBuilder启用属性:php8 原生注解 ,
            // 记得通过 导入属性类use DI\Attribute\Inject;
            $containerBuilder->useAttributes(true);
            $container = $containerBuilder->build();
            self::$container = $container;
            ApplicationContext::setContainer($container);
            return $container;
        }

        return self::$container;
    }
}

老大 我自己写的 框架 很多用这么单例 ,也不知道会不会不好,感觉怪怪的,反正我的理解 new后塞静态属性,后面就用这个静态属性,还是说 用setContainer 和 getContainer 这种方案 (就setter/getter)