Component Part1 of yii framework core

Source: Internet
Author: User

There's been a lot of buzz surrounding the use of frameworks for quite a while now and there are using great PHP frameworks to choose from. I was blown away by the simplicity and power of the base

CComponent class in the yii framework. What does the class do?

  • Properties-Adds getter and setter properties to Classes
  • Configuration-Enables an elegant class and application level cascading Configuration System
  • Events-Adds the ability to raise and call custom events
  • Behaviors-Adds the ability to use behaviors (also called mix-ins)

Every class in the framework extends fromCComponentClass, which means that all subclasses work as components and can raise and handle events as well as be reusable and retriable. This packs a lot of punch for such a little class!

I 'd like to share with you the core component that is at the heart of the yii framework, and I 've organized the tour of
CComponentClass into three articles. in this article I'll discuss how yii utilizes PHP magic methods to create class properties and an elegant Configuration System. in the next article I'll discuss how you can use Event-based programming and how
The yii component class implements this to make raising and handling events easy. the final article will walk through using behaviors (also called mix-ins), what they are, how you can use them, and how yii implements them.

So let's get started on our first topic.

Properties

A property defines a retriable aspect of a class; it exposes the class 'interface enabling you to manipulate it to do your bidding. for example, properties on an image Uploader class might be the "file path", and the "maximum allowed file size ". these
Properties can be exposed and manipulated by writing setter and getter methods such
setFilePath()AndgetFilePath(), Or simply by adding a public property on the class like
public $filePath.

However, there is a small problem with this. if you define properties as public variables you potentially have ready areas in your application that can refer to the property directly and you have no control over what other parts of the application may assign
To it. When settingfilePathProperty I may want to check if it's a valid path first and throw an error message if it's not. In order to do this I need to create
setFilePath()Method. Using$uploaderObject->filePath = "/file/path/"Just doesn' t cut it.

Yii's component class implements the magic__get()And__set()Functions which implements a devilishly simple Convention allowing you to create getter and setter methods but still access properties as if they were public variables.
Basically, yii assumes a method starting with "get" or "set" is referring to a property with the same name as the method without the "Get" or "set" prefix. this lets you easily expand your code at a later date. you can go ahead and add your public variables
When you first start building your class; don't worry about adding getter and setter methods. then you can add getter and setter methods and make the original property private but you don't have to refactor the rest of your code.

<?phpecho $uploaderObject->filePath;

Will actually call:

<?phpecho $uploader->getFilePath();

And using...

<?php$uploaderObject->filePath = "my/path";

Will call:

<?php$uploaderObject->setFilePath("my/path");

Of course you can still callgetFilePath()OrsetFilePath()Directly too if you wanted.

Let's take a look at how yii achieves this.

Yii's magic

Diving intoCComponentClass of yii you'll find the two magic methods responsible for this wizardry. Let's start with the first
__get()Function.

<?phppublic function __get($name){    $getter = "get" . $name;    if (method_exists($this, $getter)) {        return $this->$getter();    }    throw new CException("Property '$name' is not defined.");}

When you callecho $uploader->filePath;, PHP looks for the public
filePathProperty. If it doesn't find it (or if it's private), PHP will delegate to the magic Method
__get(). Php callthe__get()Function and passes it the name of the property. In this example,
$nameWill store the value "filepath". Then yii does the following:

  • Prepends the text "get" to the value of$nameVariable and assigns this to
    $getterVariable, making$getterEqual to "getfilepath" (Remember, function names in PHP are case insensitive ).
  • Checks if there is a method calledgetfilePath()Defined within this object.
  • Callthe method if it exists. The Code$this->$getter();Is really a call
    $this->getfilePath()In this example.
  • If the method isn't found then an exception will be thrown complaining, you guessed it, the property can't be found.

The same process is applied with the magic__set()Function. When you assign
setFilePathA value like so:

<?php$uploader->filePath = 'my/path';

PHP searches first for the public property. If it doesn't exist (or it's private), PHP callthe magic
__set()Function.__set()Function works in a similar way
__get(), Though PHP also passes the value you are setting, so
$value
Wocould store "My/path" in the example.

<?phppublic function __set($name, $value) {    $setter = "set" . $name;    if (method_exists($this, $setter)) {        return $this->$setter($value);    }        if (method_exists($this, "get" . $name)) {        throw new CException("Property '$name' is read only.");    }    else {        throw new CException("Property '$name' is not defined.");    }}

The implementation of__set()Function:

  • Prepends the value$nameWith "set" and assigns this
    $setter
    Variable which becomes "setfilepath ".
  • Checks if a method exists with the namesetfilePath.
  • If the method exists, then it's called like$this->setfilePath("my/path");.
  • IfsetMethod doesn't exist then a check is made if there is a getter method for the property. if there is then the property is read-only and an exception is thrown stating as much. if there is no getter and no setter method then an exception
    Is thrown stating the property does not exist.

In only a few lines of code yii has implemented a very nice property system based on using the PHP's magic
__get()And__set()Functions.

Configuration

Another advantage to using this method of defining properties is that you can easily use arrays to configure your classes if you so desire:

<?php$config = array(    "myProperty" => 1234,    "anotherProperty" => 5678);

You cocould configure your component class with the above array simply by doing the following:

<?phpforeach ($config as $property => $value) {    $this->$property = $value;}

The Code uses the array keys as properties setting them to be equal to the value defined in the array. this is amazingly simple and is how yii itself handles its application-level configuration. here's an example of a very basic demo yii configuration file:

<?phpreturn array(    "name" => "My Amazing App",    "timezone" => "Europe/London",    "components" => array(        "db" => array(            "username" => "root",            "password" => ""        ),        "user" => array(            "allowAutoLogin" => true        )    ));

The array is passed to the yii application class which then loops through each configuration key. The application class must have properties defined for "name", "timezone", and "components ".

<?phpclass MyApplication extends CComponent{    public $name;    public $timezone;    public function setComponents(array $components) {        // handle the array of components    }}

The components key callasetComponents()Function that expects an array. This function loads in each class and passes it its own array of configuration and so on until everything has its configuration properties set up. It's incredibly fast,
Completely non intrusive, and there's no need for separate configuration methods scattered throughout your code.

At a later date you can expand your class using setter and getter methods instead, if required.

<?phpclass MyApplication extends CComponent{    private $name;    private $timezone;    public setName($name) {        // do something with the $name    }    public setTimezone($timezone) {        // do something with $timezone    }    // TODO: Add getter functions     public function setComponents(array $components) {        // handle the array of components    }}
Summary

In this article I 've given you a quick snapshot of how magic methods are used in yii's component class to create properties and a simple but powerful configuration system. of course yii doesn' t stop there. it also implements the magic
__isset()And__unset()Methods, which means you can use
isset()To determine if a property has a value and useunset()To destroy the property.

In part 2 I'll talk about events, another key principle in creating highly reusable code in a component based architecture. i'll show you how you can use Event-based programming in PHP and how the yii enables its subclasses of the component to raise and
Handle events.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.