database query in action.class move to lib/model
i have:
public function executeTest(sfWebRequest $request)
{
$query = Doctrine_Query::create()
->from('Messages')
->where('id = ?', $id);
$query->fetchArray();
}
i did function in lib/model:
public function newfunction($id)
{
$query = Doctrine_Query::create()
->from('Messages')
->where('id = ?', $id);
return $query->fetchArray();
}
and now have:
public function executeTest(sfWebRequest $request)
{
$this->newfunction($id);
}
but i have error:
sfException: Call to undefined method messagesActions:开发者_StackOverflow中文版:newfunction.
if :
public function executeTest(sfWebRequest $request)
{
$this->newfunction($id);
}
i have
Fatal error: Call to a member function newFunction() on a non-object in
What can I do?
I'm assuming you created newFunction
in lib/model/MessagesTable.class.php
.
$this->newFunction()
won't work, because $this
refers to the current action instance, not your model's table. You need to use either:
Doctrine_Core::getTable("Messages")->newFunction($id);
or
MessagesTable::getInstance()->newFunction($id);
they both do the same thing, so it's just a matter of preference.
Also, you do not set a value for $id
in your action's code.
I think that you problem here is that you used a non static method in order to fetch an object using a query and the "this" reference is giving you a sfAction instance in:
public function executeTest(sfWebRequest $request)
{
$this->newfunction($id);
}
I would suggest to change your newfunction declaration in the model class to be something like this (create this funciton in /lib/model/Doctrine/MessagesTable.class.php):
public static newfunction($id)
{
$query = Doctrine_Query::create()
->from('Messages')
->where('id = ?', $id);
return $query->fetchArray();
}
Now your action should look something like this:
public function executeTest(sfWebRequest $request)
{
[..]//i'm assuming that id is set somewhere before this and is valid
MessagesTable::newfunction($id);
}
Why don't you take advantage with the 'Magic methods' that Doctrine provides?
That query could be like this:
Doctrine_Core::getTable("Messages")->findById($id);
And then, you wont need to define a new method. To see more, look at de documentation page of doctrine, into de magic method findBy*
精彩评论