In contrast to Laravel, Yii2 externalizes configuration (dependency definition) and makes up for some of the weaknesses of traits with behavior (more like weaving in Python) classes, with the benefit of dynamically extending actions. As for event handling, it is almost the same. Interestingly, yii2 borrows the set of jquery event system in naming, on,off,trigger. Of course, there are similarities, such as applications built on containers. In contrast to other domain-oriented, interface-oriented programming, Yii2 uses modules to layer, centralize small applications, and refine large architectures. Getters/setters, filters, Java traces are too obvious.
Component Component
- The main building blocks for Yii applications. is
yii\base\Component
Class or a subclass of it- It is mainly composed of Property, Event and Behavior
- Slightly heavier than regular objects, using extra memory and CPU time to process events and behaviors
- No need to use events and actions when inheritance
yii\base\Object
Supports the Property function
- Rewrite Component or Object
- Always call the parent constructor at the end of the overridden constructor
- $config is passed as the last parameter to the constructor method, called by the parent constructor and initialized before the configuration is applied
- If you override the BaseObject::init () method, make sure that the init method of the parent class is called at the beginning of the init method
- There are two ways to instantiate a component
- Instantiate the component class, New component class, component normal parameters + component configuration property parameters
- through
\Yii::createObject
Static method to create a component instance- The first array parameter class is associated with the component class name, followed by component instance properties and values
- The second array parameter is the normal parameter of the component
Yii::createObject() is implemented based on the dependency injection container
yii\base\BaseObject
The life cycle of the class at execution time- The preinitialization process within the constructor
- Configure the object with $config
- The post-initialization finishing touches are done in the init () method
- Object method calls, all the above steps are done in the constructor of the object, that is, the instance is initialized and ready to use
Attribute Property
Yii
The introduction ofyii\base\Object
Base class, which supports in-classgetter
andsetter
(reader and setter) methods to define properties- Getters and setters define property rules and restrictions
- The names of these properties are case insensitive, because PHP method names are case insensitive
- If the name of such an attribute is the same as that of a class member variable, the latter prevails
- Class attributes do not support visibility (access restrictions)
- Getter and setter methods for such properties can only be defined as non-static
- There is no magic method for uncertainty
(getter or setter
Property is called normallyproperty_exists()
Will not take effect- If there is a need, apply it
canGetProperty()
orcanSetProperty()
- If there is a need, apply it
Events Events
-
Events can “inject” custom code into specific execution points in existing code
- Append custom code to an event that is automatically executed when the event is triggered
-
Event Handlers
- The event handler is a PHP callback function, which can also be a callable object
- PHP global functions specified as strings, such as
'trim'
- An array of object and method names specifies the object method,
[$object, $method]
- Class and method names are specified as an array of static class methods, such as
[$class, $method]
- Anonymous functions, such as
function ($event) { ... }
-
The event object $event
event name
: the event nameevent sender
: The object that calls the trigger () methodcustom data
Data passed when the event handler is attached, null by default
-
Additional event handler
- Call Component class on methods such as \yii\ Base \Component::on ()
public void on ( $name, $handler, $data = null, $append = true )
-
Event Handler Order
- When an event is fired, attached handlers are called in attached order
- To stop subsequent handler calls of the same event, set the event parameter
The 'yii\base\Event:: Event' parameter is handled
Attribute to true - When the fourth argument $append is false, a new processor can be inserted at the front of the processor queue
-
Triggering Events
- Event by calling
yii\base\Component::trigger()
Methods the triggerpublic void trigger ( $name, yii\base\Event $event = null )
- Class constants are recommended for event names; the event object must be
yii\base\Event
Class or a subclass of it
- Event by calling
-
Detaching Event Handlers
public boolean off ( $name, $handler = null )
-
Class level event handlers
- Application scenarios want all instances of a class to respond to a triggered event
- Calling static methods
yii\base\Event::on()
Attach handlers at the class level- Inside the event handler, get the object that triggered the event via $event->sender
- When an object fires an event, it first invokes an instance-level handler before calling a class-level handler
- Static method yii\ Base \Event::trigger () to trigger a class-level Event, removed with off
- Remove the signature
public static boolean off ( $class, $name, $handler = null )
-
Interface events
- call
Event::on()
And take the interface class name as the first argument - You can fire this event in a class that implements the interface event, but not all classes that implement the interface
- call
-
Global event
- You need a globally accessible singleton, such as an application instance
- Instead of calling its own trigger () method, event triggers call the singleton trigger () method to trigger global events
- The advantage is that there is no need to generate an object when attaching a handler to an event to be triggered
-
Wildcard Events
- Foo.event.*, the wildcard pattern supports instance – or class-level events
behavior
-
Behaviors are instances of yII \ Base \ behaviors or subclasses of them, also known as mixins, similar to native traits
- Enhances the functionality of an existing component class without changing class inheritance
- When a behavior is attached to a component, it “injects” its methods and properties into the component
- Behavior Customizes or adjusts the code that a component normally executes by responding to events that are triggered
-
Handle events
- Let the behavior respond to the event triggered by the corresponding component, which should be overridden
yii\base\Behavior::events()
methods- The events () method of the behavior returns a list of events and the corresponding handler, specifying the event handler format as follows
- A string pointing to the method name of the behavior class
- An array of object or class names and method names, such as [$object, ‘methodName’];
- Anonymous methods
- The events () method of the behavior returns a list of events and the corresponding handler, specifying the event handler format as follows
- Let the behavior respond to the event triggered by the corresponding component, which should be overridden
-
Additional actions
- Static attachment behavior
- Overwrite behaviors using the behaviors () method of additional component classes
- The Behaviors () method returns a list of behavior configurations, each of which can be a behavior class name or an array of configurations
- Behavior can be assigned a name by specifying the corresponding key in the behavior configuration array. This behavior is called named behavior, whereas anonymous behavior or named behavior
- Dynamic additive behavior
- Called in the corresponding component
yii\base\Component::attachBehavior()
methods - or
yii\base\Component::attachBehaviors()
Method appends more than one behavior at a timepublic void attachBehaviors (array $behaviors )
- Attach behavior by configuring
- [‘ as myBehavior2 = > MyBehavior: : the className ()]
- Called in the corresponding component
- Static attachment behavior
-
Use behavior
- A public member variable must be attached to the Component class or its subclass, and then accessible by accessing the component’s behavior
- If two actions define the same property or method, and they are attached to the same component, the first to attach takes precedence
- The named behavior when attaching behavior to a component, which can be used to access behavior objects,
$component->getBehavior('myBehavior');
- Gets all the behavior attached to this component
getBehaviors()
-
Remove the behavior
- You can call
yii\base\Component::detachBehavior()
Methods are implemented with names associated with the behavior
- You can call
-
Yii2 has built-in behavior classes
yii\behaviors\TimestampBehavior
The Active Record’s timestamp property is automatically updated when it is storedyii\behaviors\BlameableBehavior
Automatically populate the specified properties with the current user IDyii\behaviors\SluggableBehavior
Automatically populates the specified property, whose value can be used as slug in the URLyii\behaviors\AttributeBehavior
Automatically assign a specified value to one or more properties of an ActiveRecord object when a specific event occursyii2tech\ar\softdelete\SoftDeleteBehavior
Provides methods for soft delete and soft restore ActiveRecordyii2tech\ar\position\PositionBehavior
Allows record order in integer fields to be managed by providing a reordering method
-
Behavior vs. Traits
- Both “inject” their own properties and methods into the main class, which is like a complementary class rather than a substitute
- Behavioral advantages
- Behavior classes support inheritance like normal classes
- Behavior can be dynamically attached to a component or removed without modifying the component class
- Behaviors are configurable, traits are not
- Behavior can be customized to the component’s code execution by responding to events
- The reason of traits
- Traits are more effective than behaviors, because behaviors are time-intensive and memory-intensive objects
- Name conflict resolution
- By prioritizing behaviors attached to the component when there may be name conflicts between different behaviors attached to the same component
- Name conflicts caused by different traits need to be resolved manually by renaming affected attributes or methods
Configuration Configurations
-
An overview of the
- Use configuration when creating new objects and initializing existing objects
- The configuration usually contains the class name of the object being created and an initial set of values to be assigned to the object properties
- It can also contain a set of handles to be attached to object events, and a set of actions to be attached to objects
-
use
- The Yii::createObject () method takes a configuration array and creates an object based on the class name specified in the array
- For existing objects, it can be used
Yii::configure()
Method to initialize its properties based on the configurationYii::configure($object, $config)
- Note If you configure an existing object, the configuration array should not contain the class element with the specified class name
-
Configuration format
class
The element specifies the fully qualified class name of the object to be createdpropertyName
The element specifies the initial value of an object property. The key name is the property name, and the value is the initial value corresponding to that property- Only public member variables and properties defined through getters/setters can be configured
on eventName
The element specifies the handle to attach to the event of the object. The array’s key name consists of the on prefix followed by the event nameas behaviorName
The element specifies the behavior to attach to the object, and the value represents the configuration information to create the behavior
-
Application Configuration
- The Application class has a number of configurable properties and events
- The Components property receives an array of configurations and is registered as a component by the application
- Yii2.0.11 + System configuration Supports the use of the Container property to configure the dependency injection container
-
Configuration of widgets
yii\base\Widget::widget()
和yii\base\Widget::begin()
Methods can be used to create widgets- By customizing its properties with the configuration, note that the configuration array does not need to contain the class key if the class name is given
-
The default configuration
Yii::createObject()
The method is implemented based on a dependency injection container- use
Yii::creatObject()
When you create an object, you can attach a set of default configurations to any instance of the specified class - The default configuration can be invoked in the entry script
Yii::$container->set()
To define the
The alias
- Setting and Parsing
- use
Yii::setAlias()
To alias the file path or URL - call
Yii::getAlias()
Command to resolve the root alias to the corresponding file path or URL
- use
- An application provides a writable attribute named aliases, which can be set in the application configuration
- Accept the alias using the alias Yii inner path property
- Yii2 Predefined alias
- Alias of the extension
- An extension installed with Composer automatically adds an alias that is defined during the boot startup phase
Automatic loading of classes
- Yii auto loader
- Each class must be placed under a namespace
- Each class must be saved as a separate file
- To add a custom namespace to the autoloader, use Yii::setAlias () to define an alias for the root directory of the namespace
- Class mapping table
- Class mapping table function, set up a mapping from the name of the class to the class file path
- When the autoloader loads a file, it first checks for the class in the mapping table
- You can use
Yii::$classMap
Method to add classes to the mapping table
- Other autoloaders
- Include yii.php (the autoloader for Yii) after the other autoloaders have been installed successfully
- Aim to make Yii the first autoloader to respond to any class autoloading request
- The Yii autoloader supports automatic loading of extended classes, requiring the autoload section to be properly defined in the composer. Json file
Service Locator
- define
- An object that provides services (or components) required by various applications
- In a service locator, each component has a single instance, uniquely identified by ID
- In Yii, the service locator is
yii\di\ServiceLocator
Or an instance of one of its subclasses
- Application scenarios
- The most common service locator is the Application object, which can be accessed via \Yii::$app
- Each module object is also a service locator in its own right, and the template can be treated as a child application
- Use the service locator
- Register related components
- through
yii\di\ServiceLocator::set()
Method to register related components. public void set ( $id, $definition )
$definition
It can be a class name, a configuration array, a PHP callable, or an instance of an object itself
- through
- Allows you to access a component by its ID as if it were a property value
- The service locator returns a singleton of the same component
yii\di\ServiceLocator::has()
Check whether a component ID is registeredyii\di\ServiceLocator::get()
- Register related components
- Tree traversal
- Modules allow arbitrary nesting; A Yii application is essentially a tree of modules
- Configurations of components in a module are never merged with configurations from components in a parent module
Dependency injection container
- The dependency injection container is an object. Know how to initialize and configure an object and all its dependent objects
Yii 通过 yii\di\Container
Class provides DI container features- Constructor injection
- The container tries to get an instance of the class or interface it depends on and then inject it into a new object through the constructor
- Methods to inject
- You can provide dependencies that are only needed by a single method of a class
- Setter and property injection
- Setters and property injection are provided through a configuration that is provided to the container to inject dependencies through the corresponding Setter or property
- PHP Callable Injection
- The container will use registered PHP callbacks to build a new instance of the class
- Constructor injection
The yii\di\Container::get() method applies its third argument as a configuration array to the object being created. If this class implements a Different interface (yII \Base \BaseObject), the yII \di\Container::get() works without any additional information. The configuration array is passed to the class constructor as the last argument
- Register dependencies
- with
yii\di\Container::set()
Register dependencies - A dependency name and a dependency definition are used for registration, and key-value pairs are recursively container-managed instances, similar to Laravel’s alias system
- The dependency name can be the class name, interface name, or an alias. The dependency definition can be the class name, configuration array, or a PHP callback
- through
set()
Registered dependencies generate a new instance each time they are used - use
yii\di\Container::setSingleton()
Register a singleton dependency
- with
- Parsing dependencies
- Dependency resolution is done recursively
- Once a dependency is registered, the container automatically resolves the dependency, instantiates the dependency, and injects the newly created object
- The name of the dependency can be passed
set()
orsetSingleton()
It can also be a list of class constructor arguments and aconfiguration
Used to configure the newly created object
- Using dependency Injection
- Introduced in the entry script of the application
Yii.php
A file,Yii
A DI container is created - The DI container can pass through
Yii::$container
access - When calling
Yii::createObject()
This method actually calls the container’s get () method to create a new object - Properties given in part calls will always override the definition in the DI container. If an error cannot be instantiated, you need to tell the container how to handle dependencies
- Introduced in the entry script of the application
- Advanced utility
- Multiple definitions can be configured at once, passing the configuration array to
setDefinitions()
orsetSingletons()
methods - Configure the array format
key
: Class name, interface name, or aliasvalue
: definition associated with class,Class association definition, 'identifies
Parameter values are passed to the set () method- Optionally, the dependency’s constructor parameter is taken as the third parameter
Instance::of('tempFileStorage')
Symbols,Container
Will implicitly provide a usetempFileStorage
Name registered dependencies- Application Scenario Internal configuration dependencies
- Dependencies registered with set () are instantiated each time they are needed
- Multiple definitions can be configured at once, passing the configuration array to
- Dependencies are registered for use
- Application development registers dependencies in the portal
- For extension development, register dependencies in the extension bootstrap class
- summary
- Yii implements its service locator on top of the dependency (DI) container
- When a service locator tries to create a new object instance, it forwards the call to the DI container
As long as you can guarantee your salary to rise a step (constantly updated)
I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx and many other knowledge points can be shared free of charge to everyone, you can join my PHP technology exchange group 953224940
>>> Architect growth path