donglie7268 2011-05-15 05:34 采纳率: 100%
浏览 28
已采纳

Cakephp变量问题 - 使用全局变量?

I'm trying to run an irc bot with cakephp. My problem is referencing the connection, I can pass it through functions but seems a silly solution when I'm writing dozens of functions all requiring the same variable. The way I did it was through a global variable $socket. It seems cakephp doesn't support global variables, at least not in the traditional sense.

Any ideas?

Here's the code:

$socket = fsockopen($config['server'], $config['port']);

The main function I will keep calling is send_data(), which communicates with the server.

function send_data($cmd, $msg = null, $socket = null)
{
                  if($msg == null)
                        {
                                fwrite($socket, $cmd."
");
                                echo '<strong>'.$cmd.'</strong><br />';
                                ob_flush();
                        } else {

                                fwrite($socket, $cmd.' '.$msg."
");
                                echo '<strong>'.$cmd.' '.$msg.'</strong><br />';
                                ob_flush();
                        }
}

So basically every time I have to call the send_data function, which I do many times, I have to reference $socket. Is there a way to make it persist in cakephp?

  • 写回答

2条回答 默认 最新

  • duagfgfn1981 2011-05-15 11:23
    关注

    The CakePHP way would be to add the socket to the model so you can then refer to it with $this->ModelName->socket. In this case you could put the send_data() function into the same model and use $this->socket inside it.

    If this is needed in several models you can add it to app_model.php so it applies to every model or make a component to use in controllers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题