praba
praba

Reputation: 105

Yii2 component function in view

I have one view, in that view i need some direct query like below,

$count = Student::find()->where(['user_id'=>yii::$app->user->identity->id])->count();

But in yii2 documentation they are not recommended this.

So i am create component class for this and then call component function in view like below,

$count = Yii::$app->mycomponent->sCount();

MyComponent.php

<?php

 namespace app\components;

 use Yii;
 use yii\base\Component;
 use app\models\Student;

 class MyComponent extends Component
 {
  public function sCount()
  {
   $count =      Student::find()->where(['user_id'=>yii::$app->user->identity->id])->count();
   return $count;
  }
 }
?>

Here all are working fine i want to know this logic is correct or this also same like in first case. Please suggest correct way.

Upvotes: 2

Views: 870

Answers (2)

Anil Chaudhari
Anil Chaudhari

Reputation: 841

Or you can supply the count as this.

public function actionIndex()
{
    $query = Student::find();
    $cloneQuery = clone $query;
    $count = $cloneQuery->where(['user_id' => Yii::$app->user->identity->id])->count();
    $models = $query->all();
    return $this->render('index', [
        'models' => $models,
        'count' => $count
    ]);
}

And access on you view like $count. * there are a lot of ways to do. But you have to follow the best practices..

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133400

If the code i largely used in several application and group a set of common funtionalities related to a specified logical area you can use components but for application related functionalties
In MVC the correct way for this is perform main procedural code and db request in controllerAction and for function model's realted the correct place should be the model itself or an extended model as eg: modelSearch for serach functions related to the mdels an pass the values you need to the view in render call eg:

so you could add (or extend) you model ad add the function

public function sCount()
{
  $count =      Student::find()->where(['user_id'=>yii::$app->user->identity->id])->count();
  return $count;
}

and refer to this function is you controller eg:

class MyController  extends Controller
{

  ......
    public function actionMyView($id)
    {

        $count = $model->sCount();
        return $this->render('view', [
            'model' => $this->findModel($id),
            'count' => $count,
        ]);
    }

then in view you can refer to $count

  echo $count;

another valid solution for avoid extra memory and CPU time to support event and behavior functionality is the use of an helpers Class .. a class for manage recurring code function not properly related to a single model

Upvotes: 2

Related Questions