Creating Yii FormModel objects (CFormModel) dynamically

非 Y 不嫁゛ 提交于 2020-01-22 08:04:21

问题


I'm working on an application that involves generating forms at a high level of abstraction (it's a CMS app). I want to dynamically create CFormModel objects and set the form fields on-the-fly. I think I can do this by extending CFormModel, and then dynamically creating the class properites that represent the form fields ('attributes' in the Yii lingo).

To illustrate, instead of specifying a login form in the following class (defined in a file):

// From: http://www.yiiframework.com/doc/guide/1.1/en/form.model
class LoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false;

    private $_identity;

    public function rules()
    {
        return array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'), // assume function authenticate defined elsewhere
        );
    }
}

I want to do it as follows:

class MyFormModel extends CFormModel {

    protected $_rules = array();

    public function __construct($attributes=array(), $rules=array()) {

        foreach ($attributes as $i => $attr) {
            $this->{$attr} = ???; // <<== This is the key here
        }

        // pass in array of rules as described in Yii doc for CFormModel
        $this->_rules = $rules;
    }

    public function rules() {
        return $_rules;
    }
}

And invoke it when needed as follows:

$myModelObj = new MyFormModel($attr, $rules);

where :

$attr = array(
            'username',
            'rememberMe',
            'password',
        );
$rules = array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'), // assume function authenticate defined elsewhere
        );

Note in what I'm trying to accomplish, there is no "LoginClass" written in any file, it's created on-the-fly in code.

This would allo me to create forms (in views) doing stuff like this:

// based on http://www.yiiframework.com/doc/guide/1.1/en/form.view
<?php echo $wForm->textField($myModelObj,'username'); ?>

etc.

I've tried this, and the $this->{$attr} line is failing with:

Property "MyFormModel.username" is not defined.

Actually the code for that line is just:

$this->{$attr};

The ??? indicates I'm not really sure what to assign to this. In the Yii doc examples, they just define the fields as public class variables.

Should I be using magic methods?

Is what I'm trying to do here even possible?


回答1:


As you probably know Yii uses OOP overloading to resolve your AR like properties.

What you need to do here is similar to what Yii internally does.

Define a hardcoded property to store all your custom properties like an array: $_data

and this data will be an array and will hold all your attributes that you added at runtime. You may need to challenge the validation by overwriting the magic methods (setters,getters,isset) as Yii does, to first resolve the property names FROM your $_data property holder.

Some sort of code you will find in CActiveRecord look for all those __XXX like methods.

If you duplicate the AR property handling to your custom class, you will get all this running at your level, and will fall back to Yii when your magic methods are not resolving it.

Also I would look into Behaviours as you can delegate a lot of common function to a behaviour class.

Use of Component Behavior

A component supports the mixin pattern and can be attached with one or several behaviors. A behavior is an object whose methods can be 'inherited' by its attached component through the means of collecting functionality instead of specialization (i.e., normal class inheritance). A component can be attached with several behaviors and thus achieve 'multiple inheritance'.

Behavior classes must implement the IBehavior interface. Most behaviors can extend from the CBehavior base class. If a behavior needs to be attached to a model, it may also extend from CModelBehavior or CActiveRecordBehavior which implements additional features specifc for models.

To use a behavior, it must be attached to a component first by calling the behavior's attach() method. Then we can call a behavior method via the component:

// $name uniquely identifies the behavior in the component
$component->attachBehavior($name,$behavior);
// test() is a method of $behavior
$component->test();

An attached behavior can be accessed like a normal property of the component. For example, if a behavior named tree is attached to a component, we can obtain the reference to this behavior object using:

$behavior=$component->tree;
// equivalent to the following:
// $behavior=$component->asa('tree');

A behavior can be temporarily disabled so that its methods are not available via the component. For example,

$component->disableBehavior($name);
// the following statement will throw an exception
$component->test();
$component->enableBehavior($name);
// it works now
$component->test();

It is possible that two behaviors attached to the same component have methods of the same name. In this case, the method of the first attached behavior will take precedence.

When used together with events, behaviors are even more powerful. A behavior, when being attached to a component, can attach some of its methods to some events of the component. By doing so, the behavior gets a chance to observe or change the normal execution flow of the component.

A behavior's properties can also be accessed via the component it is attached to. The properties include both the public member variables and the properties defined via getters and/or setters of the behavior. For example, if a behavior has a property named xyz and the behavior is attached to a component $a. Then we can use the expression $a->xyz to access the behavior's property.

More reading:
http://www.yiiframework.com/wiki/44/behaviors-events
http://www.ramirezcobos.com/2010/11/19/how-to-create-a-yii-behavior/



来源:https://stackoverflow.com/questions/11320621/creating-yii-formmodel-objects-cformmodel-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!