我试图在yii2控制器中创建简单的单例。也许我误解了这种模式,但我决定尝试。所以我有一个CRUD。当我在db中获得该类的一个实例并且我决定更新它时,$instance
变量为空(null)。是因为在创建实例后重新加载页面,以及为什么我的静态变量再次设置为null?甚至有可能让它像这样,或者我真的,真的在错误的方式?提前谢谢!
<?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']);
}
}
}
答案 0 :(得分:2)
对于设计模式,我建议您查看
对于您正在尝试的内容,最好只创建新实例。