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. isyii\base\ComponentClass 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 inheritanceyii\base\ObjectSupports 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::createObjectStatic 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\BaseObjectThe 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

  • YiiThe introduction ofyii\base\ObjectBase class, which supports in-classgetterandsetter(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 setterProperty is called normallyproperty_exists()Will not take effect
      • If there is a need, apply itcanGetProperty()orcanSetProperty()

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 asfunction ($event) { ... }
  • The event object $event

    • event name: the event name
    • event sender: The object that calls the trigger () method
    • custom dataData 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 parameterThe 'yii\base\Event:: Event' parameter is handledAttribute 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 callingyii\base\Component::trigger()Methods the trigger
      • public void trigger ( $name, yii\base\Event $event = null )
    • Class constants are recommended for event names; the event object must beyii\base\EventClass or a subclass of it
  • 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 methodsyii\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 signaturepublic static boolean off ( $class, $name, $handler = null )
  • Interface events

    • callEvent::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
  • 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 overriddenyii\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
  • 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 componentyii\base\Component::attachBehavior()methods
      • oryii\base\Component::attachBehaviors()Method appends more than one behavior at a time
        • public void attachBehaviors (array $behaviors )
      • Attach behavior by configuring
        • [‘ as myBehavior2 = > MyBehavior: : the className ()]
  • 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 componentgetBehaviors()
  • Remove the behavior

    • You can callyii\base\Component::detachBehavior()Methods are implemented with names associated with the behavior
  • Yii2 has built-in behavior classes

    • yii\behaviors\TimestampBehaviorThe Active Record’s timestamp property is automatically updated when it is stored
    • yii\behaviors\BlameableBehaviorAutomatically populate the specified properties with the current user ID
    • yii\behaviors\SluggableBehaviorAutomatically populates the specified property, whose value can be used as slug in the URL
    • yii\behaviors\AttributeBehaviorAutomatically assign a specified value to one or more properties of an ActiveRecord object when a specific event occurs
    • yii2tech\ar\softdelete\SoftDeleteBehaviorProvides methods for soft delete and soft restore ActiveRecord
    • yii2tech\ar\position\PositionBehaviorAllows 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 usedYii::configure()Method to initialize its properties based on the configuration
      • Yii::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

    • classThe element specifies the fully qualified class name of the object to be created
    • propertyNameThe 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 eventNameThe 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 name
    • as behaviorNameThe 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
    • useYii::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 scriptYii::$container->set()To define the

The alias

  • Setting and Parsing
    • useYii::setAlias()To alias the file path or URL
    • callYii::getAlias()Command to resolve the root alias to the corresponding file path or URL
  • 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 useYii::$classMapMethod 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 isyii\di\ServiceLocatorOr 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
      • throughyii\di\ServiceLocator::set()Method to register related components.
      • public void set ( $id, $definition )
      • $definitionIt can be a class name, a configuration array, a PHP callable, or an instance of an object itself
    • 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 registered
      • yii\di\ServiceLocator::get()
  • 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\ContainerClass 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

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
    • withyii\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
    • throughset()Registered dependencies generate a new instance each time they are used
    • useyii\di\Container::setSingleton()Register a singleton dependency
  • 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 passedset()orsetSingleton()It can also be a list of class constructor arguments and aconfigurationUsed to configure the newly created object
  • Using dependency Injection
    • Introduced in the entry script of the applicationYii.phpA file,YiiA DI container is created
    • The DI container can pass throughYii::$containeraccess
    • When callingYii::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
  • Advanced utility
    • Multiple definitions can be configured at once, passing the configuration array tosetDefinitions()orsetSingletons()methods
    • Configure the array format
      • key: Class name, interface name, or alias
      • value: definition associated with class,Class association definition, 'identifiesParameter values are passed to the set () method
      • Optionally, the dependency’s constructor parameter is taken as the third parameter
      • Instance::of('tempFileStorage')Symbols,ContainerWill implicitly provide a usetempFileStorageName registered dependencies
        • Application Scenario Internal configuration dependencies
    • Dependencies registered with set () are instantiated each time they are needed
  • 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