dqnqpqv3841 2012-07-03 14:28
浏览 42
已采纳

如何为查找数据库表定义ActiveRecord,以便它与枚举常量一样有用?

We have an Yii-based PHP application which does some generic actions (like "Share" with social networks or "Buy" in internal web shop) on different types of objects.

Right now developers use the class constants to separate objects of different types. Like so:

in model:

class Referral extends CActiveRecord {
    //... a lot more stuff here...
    const ITEM_TYPE_PRODUCT = 'product';
    const ITEM_TYPE_DESIGN = 'design';
    const ITEM_TYPE_BRAND = 'brand';
    const ITEM_TYPE_INVITE = 'invite';
    const ITEM_TYPE_DESIGNER = 'designer';
    //... a lot more stuff here...
}

then later in some controller:

// calling static method of Referral and pass a type IDs to change it's behavior
$referral_params = Referral::buildReferallParams(
    Referral::TYPE_PINTEREST, 
    Referral::ITEM_TYPE_PRODUCT
)

This usage of class constants has led to major code duplication which I want to move away.

I personally think we should really add a lookup table for types, like so:

CREATE TABLE `item_type` (
    id int primary key auto_increment,
    name varchar(255)
);

And make a Yii model class named ItemType to extract IDs from the table with.

But it leads to another problem: we need to use this type IDs in the code anyway and will need to do so for a long time. We need to make a symbolic names for IDs somehow. Right now the call like Referral::ITEM_TYPE_PRODUCT is very convenient, and to change it to Yii-flavored ItemType::model()->findByAttributes(array('name' => 'Product')) is totally unacceptable.

I want to avoid maintaining the same list of class constants (which is duplicated now through our codebase) in the ItemType because each addition of new type will require addition of new constants and it's just a out-of-sync problem waiting to occur.

So, the question is as follows: how to make an ActiveRecord for a lookup table equally useful as the 'enum'-like set of numeric constants?

I came with the following somewhat beautiful solution, using the subclasses of ItemType:

ProductItemType::id(); // returns lazy-loaded ID for 'Product' item type
BrandItemType::id();   // the same for 'Brand' item type
// ... and so on

But if requires five subclasses of single base class right now and maybe another half of dozen more later. Is there any viable architectural solution?

EDIT

Problem with duplication is this: class constants declaring type IDs become redefined in every class which needs to somehow differentiate between different item types. I know that the most "true" solution would be to invert this inside out and move the features which depends on the type of object to the objects itself, but we have legacy code without any test coverage and this solution is just a dream right now. Right now all I want to do is remove this duplication. And constants, too.

  • 写回答

1条回答 默认 最新

  • duange051858 2012-07-05 13:34
    关注

    Well if you want all these defined one time, and to take from the database. That means you need to do a behaviour, have static like methods to retrieve these (so constants will become functions), you will need to create the proper magic method __call to override these non existent functions to call your database, and you can attach this behavior to any yii class you are using.

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法