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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分