khartvin
khartvin

Reputation: 571

calling a function from action in symfony 1.4

I'm in need of calling a function located in a class stored in app/lib directory before every action (ie. in preExecute action)

In that function I do need a $this pointer from an action.

I can do it in a static way - Classname::functionname(), however it results with a PHP warning, which I want to avoid.

For now I handle it with

ini_set('display_errors', '0');     # don't show any errors...
error_reporting(E_ALL | E_STRICT);  # ...but do log them

but it's an ugly way..

How can I do it in a dynamic way?

===============

EDIT:

as requested - I add a code to show what am I actually doing with that $this pointer

...
$c = new Criteria();
$c->add(ArticlePeer::PUBLISHED, true);
$articles = ArticlePeer::doSelect($c);
$this->articles = $articles;
...

Yes, I know that I can put this Select in preExecute action in every module and it will be working fine. However - I have many modules, and as I have a set of actions that are all the same for all those modules, so putting them in one procedure and just calling that function would be the smartest way... Especially when it comes to maintaining the app - It's only one place to change code, instead of a dozen of them...

Upvotes: 0

Views: 1870

Answers (2)

j0k
j0k

Reputation: 22756

In your class inside your app/lib folder, you simply have to return $articles:

$c = new Criteria();
$c->add(ArticlePeer::PUBLISHED, true);
return ArticlePeer::doSelect($c);

Then, inside your preExecute():

public function preExecute()
{
  $this->articles = Classname::functionname();
}

If you have to return multiple value, you can do it using an array:

$c = new Criteria();
$c->add(ArticlePeer::PUBLISHED, true);
$articles =  ArticlePeer::doSelect($c);

$c = new Criteria();
$c->add(BookPeer::PUBLISHED, true);
$books =  BookPeer::doSelect($c);

return array(
  'articles' => $articles,
  'books'    => $books,
);

End then, use this array to populate your variable inside your action:

public function preExecute()
{
  $data = Classname::functionname();

  $this->articles = $data['articles'];
  $this->books    = $data['books'];
}

Upvotes: 1

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

You cannot change the value of $this in a method. Never.

Instead, look at the class how you can access $articles from outside, there should be something like getArticles(). It looks like the class is a Propel model, those have generated getters like that.

Dependent on what your end goal is, there might be better solutions than instantiating this model, calling the mysterious method and then getting the attribute. After all, classes are not just collections of functions and should not be treated like that. Not repeating code is good, but it has to be done with some sense.

Upvotes: 0

Related Questions