如何在没有数据库的情况下创建 Yii2 模型 [英] How to create a Yii2 model without a database

查看:35
本文介绍了如何在没有数据库的情况下创建 Yii2 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个没有数据库的 yii2 模型.相反,数据是动态生成的而不是存储的,只是作为 json 显示给用户.基本上,我只想得到一个非数据库模型工作的简单、基本示例,但我找不到关于它的任何文档.

那么我将如何在没有数据库的情况下编写模型?我已经扩展了 \yii\base\Model 但我收到以下错误消息:

要实现find(),我必须返回一个数据库查询对象.

我的模型完全空白,我只是想找一个简单的例子来理解原理.

解决方案

这是我的一个项目中的 Model.此Model 未连接任何数据库.

150],//应用后端主题['appBackendTheme', 'required'],//应用前端主题['appFrontendTheme', 'required'],//缓存类['cacheClass', '必需'],['cacheClass', 'string', 'max' =>128],//应用之旅['appTour', '布尔值']];}公共函数attributeLabels(){返回 ['应用程序名称' =>'应用名称','appFrontendTheme' =>'前端主题','appBackendTheme' =>'后端主题','缓存类' =>'缓存类','appTour' =>'为新用户展示介绍之旅'];}}

像其他任何东西一样使用这个 Model.例如view.php:

title = '基本设置 - ' .Yii::$app->name;?><div class="panel panel-default"><div class="panel-heading">基本设置</div><div class="panel-body"><?= $this->render('/alert') ?><?php $form = ActiveForm::begin(['id' =>'基本设置形式','enableAjaxValidation' =>错误的,]);?><h4>应用程序设置</h4><div class="form-group"><?= $form->field($model, 'appName')->textInput(['价值' =>Yii::$app->config->get(枚举::APP_NAME, '初学者工具包'),'自动对焦' =>真的,'自动完成' =>'离开'])?>

<小时/><h4>主题设置</h4><div class="form-group"><?= $form->field($model, 'appBackendTheme')->dropDownList($themes, ['类' =>'形式控制','选项' =>[Yii::$app->config->get(Enum::APP_BACKEND_THEME, 'yeti') =>['选择' =>真的]]]) ?>

<div class="form-group"><?= $form->field($model, 'appFrontendTheme')->dropDownList($themes, ['类' =>'形式控制','选项' =>[Yii::$app->config->get(Enum::APP_FRONTEND_THEME, 'readable') =>['选择' =>真的]]]) ?>

<小时/><h4>缓存设置</h4><div class="form-group"><?= $form->field($model, 'cacheClass')->dropDownList([FileCache::className() =>'文件缓存',DbCache::className() =>'数据库缓存'],['类' =>'形式控制','选项' =>[Yii::$app->config->get(Enum::CACHE_CLASS, FileCache::className()) =>['选择' =>真的]]]) ?>

<小时/><h4>介绍之旅</h4><div class="form-group"><div class="checkbox"><?= $form->field($model, 'appTour')->checkbox() ?>

<?= Html::submitButton('Save', ['class' =>'btn btn-primary']) ?><?php $form::end();?>

I would like to create a yii2 model without a database. Instead, the data is generated dynamically and not stored, just displayed to the user as a json. Basically, I would just like a get a simple, basic example of a non-database Model working but I can't find any documentation on it.

So how would I write a model without a database? I have extended \yii\base\Model but I get the following error message:

<?xml version="1.0" encoding="UTF-8"?>
<response>
   <name>PHP Fatal Error</name>
   <message>Call to undefined method my\app\models\Test::find()</message>
   <code>1</code>
   <type>yii\base\ErrorException</type>
   <file>/my/app/vendor/yiisoft/yii2/rest/IndexAction.php</file>
   <line>61</line>
   <stack-trace>
      <item>#0 [internal function]: yii\base\ErrorHandler->handleFatalError()</item>
      <item>#1 {main}</item>
   </stack-trace>
</response>

To implement find(), I must return a database query object.

My Model is completely blank, I'm just looking for a simple example to understand the principal.

<?php
namespace my\app\models;

class Test extends \yii\base\Model{
}

解决方案

This is a Model from one of my projects. This Model is not connected with any database.

<?php
/**
 * Created by PhpStorm.
 * User: Abhimanyu
 * Date: 18-02-2015
 * Time: 22:07
 */

namespace backend\models;

use yii\base\Model;

class BasicSettingForm extends Model
{
    public $appName;
    public $appBackendTheme;
    public $appFrontendTheme;
    public $cacheClass;
    public $appTour;

    public function rules()
    {
        return [
            // Application Name
            ['appName', 'required'],
            ['appName', 'string', 'max' => 150],

            // Application Backend Theme
            ['appBackendTheme', 'required'],

            // Application Frontend Theme
            ['appFrontendTheme', 'required'],

            // Cache Class
            ['cacheClass', 'required'],
            ['cacheClass', 'string', 'max' => 128],

            // Application Tour
            ['appTour', 'boolean']
        ];
    }

    public function attributeLabels()
    {
        return [
            'appName'          => 'Application Name',
            'appFrontendTheme' => 'Frontend Theme',
            'appBackendTheme'  => 'Backend Theme',
            'cacheClass' => 'Cache Class',
            'appTour'    => 'Show introduction tour for new users'
        ];
    }
}

Use this Model like any other. e.g. view.php:

<?php
/**
 * Created by PhpStorm.
 * User: Abhimanyu
 * Date: 18-02-2015
 * Time: 16:47
 */

use abhimanyu\installer\helpers\enums\Configuration as Enum;
use yii\caching\DbCache;
use yii\caching\FileCache;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/** @var $this \yii\web\View */
/** @var $model \backend\models\BasicSettingForm */
/** @var $themes */

$this->title = 'Basic Settings - ' . Yii::$app->name;
?>

<div class="panel panel-default">
    <div class="panel-heading">Basic Settings</div>

    <div class="panel-body">

        <?= $this->render('/alert') ?>

        <?php $form = ActiveForm::begin([
                                        'id'                   => 'basic-setting-form',
                                        'enableAjaxValidation' => FALSE,
                                    ]); ?>

        <h4>Application Settings</h4>

        <div class="form-group">
            <?= $form->field($model, 'appName')->textInput([
                                                           'value'        => Yii::$app->config->get(
                                                               Enum::APP_NAME, 'Starter Kit'),
                                                           'autofocus'    => TRUE,
                                                           'autocomplete' => 'off'
                                                       ])
            ?>
        </div>

        <hr/>

        <h4>Theme Settings</h4>

        <div class="form-group">
            <?= $form->field($model, 'appBackendTheme')->dropDownList($themes, [
            'class'   => 'form-control',
            'options' => [
                Yii::$app->config->get(Enum::APP_BACKEND_THEME, 'yeti') => ['selected ' => TRUE]
            ]
        ]) ?>
    </div>

    <div class="form-group">
        <?= $form->field($model, 'appFrontendTheme')->dropDownList($themes, [
            'class'   => 'form-control',
            'options' => [
                Yii::$app->config->get(Enum::APP_FRONTEND_THEME, 'readable') => ['selected ' => TRUE]
            ]
        ]) ?>
    </div>

    <hr/>

    <h4>Cache Setting</h4>

    <div class="form-group">
        <?= $form->field($model, 'cacheClass')->dropDownList(
            [
                FileCache::className() => 'File Cache',
                DbCache::className()   => 'Db Cache'
            ],
            [
                'class'   => 'form-control',
                'options' => [
                    Yii::$app->config->get(Enum::CACHE_CLASS, FileCache::className()) => ['selected ' => TRUE]
                ]
            ]) ?>
    </div>

    <hr/>

    <h4>Introduction Tour</h4>

    <div class="form-group">
        <div class="checkbox">
            <?= $form->field($model, 'appTour')->checkbox() ?>
        </div>
    </div>

    <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>

    <?php $form::end(); ?>
</div>

这篇关于如何在没有数据库的情况下创建 Yii2 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆