How to access database from configure method of a symfony task
You can create a symfony "task" by extending sfBaseTask
; see http://www.symfony-project.org/cookbook/1_1/en/task开发者_开发问答s for more details.
However, I cannot see how to set up a database connection in the configure
section. I want to do this so that I can have the detailedDescription
property show some options that are only defined in the database.
What is the best way to do this?
If you check out the way symfony creates a custom Task Skeleton (./symfony generate:task yourTaskName
), you would see code that looks like this inside the execute function:
protected function execute([..])
{
$databaseManager = new sfDatabaseManager($this->configuration);
$connection = $databaseManager->getDatabase($options['connection'])->getConnection();
[..]
The problem with this code is that it uses the default configuration, but if you know what connection you want to open (check your database.yml
or schema.yml
to figure out the name) it should be really easy, with code that looks like this:
protected function configure()
{
$databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration('frontend', 'prod', true));
$connection = $databaseManager->getDatabase("the_name_of_your_connection")->getConnection();
[..]
Then you can access your models the usual way, e.g.:
$myItem = Doctrine_Core::getTable('item')->find(14);
echo $myItem->getId();
If you are using Doctrine, the best way to do that is defining a method into the php model file. The model's files are located into /PROJECT/lib/model/doctrine/MODEL_NAMETable.class.php
Be carefull with the MVC model!
Once you have your own method, the way to call it is: Doctrine_Core::getTable('TABLE_NAME')->miNewMethod($params-if-any);
I hope I'll help you!
精彩评论