IndexAction.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\rest;
  8. use Yii;
  9. use yii\data\ActiveDataProvider;
  10. /**
  11. * IndexAction implements the API endpoint for listing multiple models.
  12. *
  13. * For more details and usage information on IndexAction, see the [guide article on rest controllers](guide:rest-controllers).
  14. *
  15. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @since 2.0
  17. */
  18. class IndexAction extends Action
  19. {
  20. /**
  21. * @var callable a PHP callable that will be called to prepare a data provider that
  22. * should return a collection of the models. If not set, [[prepareDataProvider()]] will be used instead.
  23. * The signature of the callable should be:
  24. *
  25. * ```php
  26. * function ($action) {
  27. * // $action is the action object currently running
  28. * }
  29. * ```
  30. *
  31. * The callable should return an instance of [[ActiveDataProvider]].
  32. */
  33. public $prepareDataProvider;
  34. /**
  35. * @return ActiveDataProvider
  36. */
  37. public function run()
  38. {
  39. if ($this->checkAccess) {
  40. call_user_func($this->checkAccess, $this->id);
  41. }
  42. return $this->prepareDataProvider();
  43. }
  44. /**
  45. * Prepares the data provider that should return the requested collection of the models.
  46. * @return ActiveDataProvider
  47. */
  48. protected function prepareDataProvider()
  49. {
  50. if ($this->prepareDataProvider !== null) {
  51. return call_user_func($this->prepareDataProvider, $this);
  52. }
  53. /* @var $modelClass \yii\db\BaseActiveRecord */
  54. $modelClass = $this->modelClass;
  55. return Yii::createObject([
  56. 'class' => ActiveDataProvider::className(),
  57. 'query' => $modelClass::find(),
  58. ]);
  59. }
  60. }