2017-08-29 87 views
0

我想在yii2控制器中創建簡單的單身人士。也許我誤解了這種模式,但我決定嘗試。所以我有一個CRUD。當我在db中獲得該類的一個實例並決定更新它時,$instance變量爲空(空)。是否是因爲在創建實例後重新加載頁面,這就是爲什麼我的靜態變量再次設置爲空的原因?是甚至有可能使這樣或我真的,真的在錯誤的方式嗎?先謝謝你!Yii2創建簡單的單身人士

<?php 

namespace backend\controllers; 

use backend\models\DeliveryTime; 
use yii\data\ActiveDataProvider; 
use Yii; 

class DeliveryTimeController extends \yii\web\Controller 
{ 

    public static $instance = null; 

    public function actionIndex() 
    { 
     $delivery = new ActiveDataProvider([ 
      'query' => DeliveryTime::find()->where('id>0') 
     ]); 
     return $this->render('index', ['delivery' => $delivery]); 
    } 

    public static function setInstance() 
    { 
     if(self::$instance == null){ 
      self::$instance = new DeliveryTime(); 
     } 
     return self::$instance; 
    } 

    public static function getInstance(){ 
     return self::$instance; 
    } 

    public function actionCreate() 
    { 
     $delivery = DeliveryTimeController::setInstance(); 

     if($delivery->load(Yii::$app->request->post()) && $delivery->save()){ 
      self::$instance = $delivery; 
      return $this->redirect(['index']); 
     } 

     return $this->render('create', ['model' => $delivery]); 
    } 

    public function actionUpdate() 
    { 
     $delivery = DeliveryTimeController::getInstance(); 

     if($delivery->load(Yii::$app->request->post()) && $delivery->save()){ 
      return $this->render(['index']); 
     } 
     return $this->render('update', ['model' => $delivery]); 
    } 

    public function actionDelete(){ 
     $delivery = DeliveryTimeController::getInstance(); 
     if($delivery != null){ 
      $delivery->delete(); 
      return $this->redirect(['index']); 
     } 
    } 

} 

回答