IndexAction.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-08-13 01:00
  7. */
  8. namespace backend\actions;
  9. use Yii;
  10. use Closure;
  11. use backend\actions\helpers\Helper;
  12. use yii\base\Exception;
  13. /**
  14. * Index list page
  15. *
  16. * Class IndexAction
  17. * @package backend\actions
  18. */
  19. class IndexAction extends \yii\base\Action
  20. {
  21. /**
  22. * @var string|array primary key(s) name
  23. */
  24. public $primaryKeyIdentity = null;
  25. /**
  26. * @var string primary keys(s) from (GET or POST)
  27. */
  28. public $primaryKeyFromMethod = "GET";
  29. /**
  30. * @var array|\Closure assign to view variables
  31. */
  32. public $data;
  33. /** @var $viewFile string template view file path, default is action id */
  34. public $viewFile = null;
  35. /**
  36. * index list
  37. *
  38. * @return string
  39. * @throws Exception
  40. */
  41. public function run()
  42. {
  43. //according assigned HTTP Method and param name to get value. will be passed to $this->>data closure.Often there is no need to get value on index, so default value is null.
  44. $primaryKeys = Helper::getPrimaryKeys($this->primaryKeyIdentity, $this->primaryKeyFromMethod);
  45. $data = $this->data;
  46. if( $data instanceof Closure){
  47. $params = [];
  48. if( !empty($primaryKeys) ){
  49. foreach ($primaryKeys as $primaryKey) {
  50. array_push($params, $primaryKey);
  51. }
  52. }
  53. array_push($params, Yii::$app->getRequest()->getQueryParams());
  54. array_push($params, $this);
  55. //execute closure then assign to view, the closure params like function($_GET, primaryKeyValue1, primaryKeyValue1 ..., IndexAction)
  56. $data = call_user_func_array( $this->data, $params );
  57. if( !is_array($data) ){
  58. throw new Exception("data closure must return array");
  59. }
  60. }else if (!is_array($data) ){
  61. throw new Exception(__CLASS__ . "::data must be array or closure");
  62. }
  63. //default view template is action id
  64. $this->viewFile === null && $this->viewFile = $this->id;
  65. return $this->controller->render($this->viewFile, $data);
  66. }
  67. }