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?
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.
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
精彩评论