Simplify repetitive queries in multiple actions


I am trying to figure out if I can simplify the code I am writing.

Currently I have a AR model named SiteModel, and a controller named SiteController.

In this SiteController I have a various number of actions e.g. actionPageone, actionPagetwo, etc.

Inside these actions I am calling a query as followed:

$query = SiteModel::model()->findAllByAttributes(array(

'ID' => 1


Since I have the same query in every action I was wondering if there is a more simplified approach I could take instead of having redundant code.

it is not clear what you are trying to achieve. why do you have an action for each page?

Add an actionPage to your controller like this:

public function actionPage($id) 




  $query = SiteModel::model()->findAllByAttributes(array(

    'ID' => $id






and call this url like .../site/page/1 or .../site/page/id/1 with urlmanager enabled in config/main.php.

Add additional code / rules to check first if the $id param is correct (integer …)



[size=2]Sorry, the word ‘page’ might have been misleading here. It better be ‘view’. Since I need different logic in each view I need a separate action for each view.[/size]

Thanks for this suggestions but I guess this will only work if the logic for each each view will be the same?!

Hi jrn,

Create a method and in your controller:

private function getSiteModel(){

    return SiteModel::model()->findAllByAttributes(array(

        'ID' => 1



and just use it like

    $query = $this->getSiteModel();

whenever you want to use it.

Thanks a lot macinville.

That is the approach I will take.

Would I somehow be able to create a ‘magic method’ which gets executed every time so I could have a global variable defined within the method you wrote?

Not sure that I understood you right, but maybe you’re looking for scopes (also have a look at default scope)

Hi jrn,

What exactly do you mean by ‘magic method’? Kindly explain the details of what you want to accomplish.:)

Oh nevermind. You guys fully answered my question. Sorry about this :)

My bad.

you can also handle ‘beforeAction’:

function beforeAction( $action ) {

  $this->site = SiteModel::model()->findAllByAttributes(array(

        'ID' => 1


  return parent::beforeAction( $action );


and then access local attribute ‘site’ in actions:

$query = $this->site->XXX

This aproach is more “magic” because ‘$this->site’ is instantiated automagically on every request ;)

This sounds like a good idea, redguy!

I will give it a shot. Thanks :)