Google News
logo
Yii framework - Interview Questions
What about Data Providers in Yii framework?
In the Pagination and Sorting sections, we have described how to allow end users to choose a particular page of data to display and sort them by some columns. Because the task of paginating and sorting data is very common, Yii provides a set of data provider classes to encapsulate it.
 
A data provider is a class implementing yii\data\DataProviderInterface. It mainly supports retrieving paginated and sorted data. It is usually used to work with data widgets so that end users can interactively paginate and sort data.
 
The following data provider classes are included in the Yii releases :
 
yii\data\ActiveDataProvider : uses yii\db\Query or yii\db\ActiveQuery to query data from databases and return them in terms of arrays or Active Record instances.

yii\data\SqlDataProvider : executes a SQL statement and returns database data as arrays.

yii\data\ArrayDataProvider : takes a big array and returns a slice of it based on the paginating and sorting specifications.

The usage of all these data providers share the following common pattern :
// create the data provider by configuring its pagination and sort properties
$provider = new XyzDataProvider([
    'pagination' => [...],
    'sort' => [...],
]);

// retrieves paginated and sorted data
$models = $provider->getModels();

// get the number of data items in the current page
$count = $provider->getCount();

// get the total number of data items across all pages
$totalCount = $provider->getTotalCount();
You specify the pagination and sorting behaviors of a data provider by configuring its pagination and sort properties which correspond to the configurations for yii\data\Pagination and yii\data\Sort, respectively. You may also configure them to be false to disable pagination and/or sorting features.
 
Data widgets, such as yii\grid\GridView, have a property named dataProvider which can take a data provider instance and display the data it provides. For example :
echo yii\grid\GridView::widget([
    'dataProvider' => $dataProvider,
]);
Advertisement