Cakephp变量问题-使用全局变量?
我正在尝试使用 cakephp 运行 irc 机器人。我的问题是引用连接,我可以通过函数传递它,但当我编写数十个都需要相同变量的函数时,这似乎是一个愚蠢的解决方案。我的方法是通过全局变量 $socket。看来cakephp不支持全局变量,至少不是传统意义上的。
有什么想法吗?
代码如下:
$socket = fsockopen($config['server'], $config['port']);
我将继续调用的主要函数是 send_data(),它与服务器进行通信。
function send_data($cmd, $msg = null, $socket = null)
{
if($msg == null)
{
fwrite($socket, $cmd."\r\n");
echo '<strong>'.$cmd.'</strong><br />';
ob_flush();
} else {
fwrite($socket, $cmd.' '.$msg."\r\n");
echo '<strong>'.$cmd.' '.$msg.'</strong><br />';
ob_flush();
}
}
所以基本上每次我必须调用 send_data 函数(我这样做了很多次)时,我都必须引用 $socket。有没有办法让它在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."\r\n");
echo '<strong>'.$cmd.'</strong><br />';
ob_flush();
} else {
fwrite($socket, $cmd.' '.$msg."\r\n");
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CakePHP 的方法是将套接字添加到模型中,以便您可以使用
$this->ModelName->socket
引用它。在这种情况下,您可以将 send_data() 函数放入同一模型中,并在其中使用$this->socket
。如果多个模型需要此功能,您可以将其添加到
app_model.php
中,以便它适用于每个模型或制作一个在控制器中使用的组件。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.我部分同意 Juhana 的观点,即您应该通过模型而不是组件来隔离代码。如果您要遵循真正的 MVC 模式,您可以将其保留在模型中,但行为可能是最佳实践。
我建议研究行为并看看它是否适用于您的数据模型。
http://book.cakephp.org/view/1071/Behaviors
I partially agree with Juhana on this in which you should segregate the code via a model, not as a component. If you were to follow a true MVC pattern, you could stick it in a model, but a behavior might be the best practice.
I'd suggest looking into behaviors and see if it works with your data model.
http://book.cakephp.org/view/1071/Behaviors