search
HomeBackend DevelopmentPHP TutorialYii Framework Official Guide Series 10 - Basics: Components



Yii applications are built on components. Components are instances of CComponent or its subclasses. Using a component mainly involves accessing its properties and when to trigger or handle it. The base class CComponent specifies how properties and events are defined.

1. Component properties

The properties of a component are like the public member variables of an object. It is readable and writable. For example:


$width=$component->textWidth;     // 获取 textWidth 属性
$component->enableCaching=true;   // 设置 enableCaching 属性

To define a component property, we only need to define a public member variable in the component class . A more flexible way is to define its getter and setter methods, for example:


public function getTextWidth()
{
    return $this->_textWidth;
}

public function setTextWidth($value)
{
    $this->_textWidth=$value;
}

The above code defines a writable The attribute name is textWidth (the name is case-insensitive). When reading properties, getTextWidth() will be called, and its return value becomes the property value; similarly, when writing properties, setTextWidth() will be called. If the setter method is not defined, the property will be read-only and an exception will be thrown if written to it. One benefit of defining a property using getter and setter methods is that additional logic can be performed (e.g., performing validations, triggering events) when the property is read or written.

Note: There is a subtle difference between properties defined through getters/setters and class member variables. The former's name is case-insensitive, while the latter's is case-sensitive.

2. Component events

Component events are special properties that use methods called event handlers as its value. Attaching (assigning) a method to an event will cause the method to be automatically called when the event is raised. Therefore, the behavior of a component may be modified in a way that was unforeseen during component development.

Component events are defined using naming methods starting with on. Like properties defined through getter/setter methods, event names are case-insensitive. The following code defines an onClicked event:


public function onClicked($event)
{
    $this->raiseEvent('onClicked', $event);
}

used as event parameters here $event is an instance of CEvent or one of its subclasses.

We can attach a method to this event as follows:


$component->onClicked=$callback;

Here $callback points to a valid PHP callback. It can be a global function or a method in a class. If it is the latter, it must be provided as an array: array($object,'methodName').

The structure of the event handler is as follows:


function methodName($event)
{
    ......
}

The $event here is the parameter describing the event (it comes from the raiseEvent() call) . $event The parameter is an instance of CEvent or its subclass. At the very least, it contains information about who triggered the event.

Starting from version 1.0.10, the event handler can also be an anonymous function supported by PHP 5.3 or later. For example,


##

$component->onClicked=function($event) {
    ......
}

If we now call

onClicked(), onClicked The event will be triggered (in onClicked()), and the attached event handler will be automatically called.

An event can be bound to multiple handles. When an event fires, these handlers will be executed in the order in which they were bound to the event. If the handler decides to prevent subsequent handlers from being executed, it can set $event->handled to true.

3. Component Behavior

Starting from version 1.0.2, the component has added support for mixin and can bind one or more behaviors.

Behavior is an object whose methods can be implemented by the components it is bound to by collecting functions inherited, rather than specialized inheritance (i.e. ordinary class inheritance) ). A component can implement the binding of multiple behaviors through 'multiple inheritance'.

The behavior class must implement the IBehavior interface. Most behaviors can be inherited from CBehavior . If a behavior needs to be bound to a model, it can also inherit from CModelBehavior or CActiveRecordBehavior which implement binding features specifically for the model.

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


// $name 在组件中实现了对行为的唯一识别
$component->attachBehavior($name,$behavior);
// test() 是行为中的方法。
$component->test();

The bound behavior can be like in a component Accessed like normal properties. For example, if a behavior named

tree is bound to a component, we can get a reference to this behavior through the following code.


$behavior=$component->tree;
// 等于下行代码:
// $behavior=$component->asa('tree');

Behavior can be temporarily disabled, at which time its method will become invalid in the component. For example :


$component->disableBehavior($name);
// 下面的代码将抛出一个异常
$component->test();
$component->enableBehavior($name);
// 现在就可以使用了
$component->test();

两个同名行为绑定到同一个组件下是有可能的。在这种情况下,先绑定的行为则拥有优先权。

当和 events, 一起使用时,行为会更加强大。当行为被绑定到组件时,行为里的一些方法就可以绑定到组件的一些事件上了. 这样一来,行为就可以观察或者改变组件的常规执行流程。

自版本 1.1.0 开始,一个行为的属性也可以通过绑定到的组件来访问。 这些属性包含公共成员变量以及通过 getters 和/或 setters 方式设置的属性。 例如, 若一个行为有一个 xyz 的属性,此行为被绑定到组件 $a,然后我们可以使用表达式 $a->xyz 访问此行为的属性。

以上就是Yii框架官方指南系列10——基础知识:组件的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools