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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献