ViewAction.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-08-13 10:10
  7. */
  8. namespace backend\actions;
  9. use Closure;
  10. use backend\actions\helpers\Helper;
  11. use yii\base\Exception;
  12. /**
  13. * backend view single record
  14. *
  15. * Class ViewAction
  16. * @package backend\actions
  17. */
  18. class ViewAction extends \yii\base\Action
  19. {
  20. /**
  21. * @var string|array primary key(s) name
  22. */
  23. public $primaryKeyIdentity = 'id';
  24. /**
  25. * @var string primary keys(s) from (GET or POST)
  26. */
  27. public $primaryKeyFromMethod = "GET";
  28. /** @var array|Closure variables will assigned to view */
  29. public $data;
  30. /**
  31. * @var string view template file path, default is action id
  32. */
  33. public $viewFile = 'view';
  34. /**
  35. * view detail page
  36. *
  37. * @return string
  38. * @throws Exception
  39. */
  40. public function run()
  41. {
  42. if( is_array($this->data) ){
  43. $data = $this->data;
  44. }else if ($this->data instanceof Closure){
  45. //according assigned HTTP Method and param name to get value. will be passed to $this->data closure.Often use for get value of primary key.
  46. $primaryKeys = Helper::getPrimaryKeys($this->primaryKeyIdentity, $this->primaryKeyFromMethod);
  47. $getDataParams = $primaryKeys;
  48. array_push($getDataParams, $this);
  49. $data = call_user_func_array($this->data, $getDataParams);
  50. if( !is_array($data) ){
  51. throw new Exception(__CLASS__ . "::data closure must return array");
  52. }
  53. }else{
  54. throw new Exception(__CLASS__ . "::data only allows array or closure (with return array)");
  55. }
  56. return $this->controller->render($this->viewFile, $data);
  57. }
  58. }