Yii 2 Framework

repository·master·Indexed 12 days ago

https://github.com/yiisoft/yii2

A modern, fast, and secure PHP framework designed for professional web development. Yii 2.0 provides a flexible foundation for web applications with a comprehensive feature set including an Active Record ORM, Gii code generator, Dependency Injection container, and robust support for RESTful web services, security (RBAC), and multiple caching strategies.

Tokens
200.4K
Snippets
617
Records
836
Agent score
93%

What's inside Yii

  1. Explore Core Yii 2 Extensions

    master

    Yii provides several core extensions maintained by the Yii developer team. These extensions add specialized functionality such as database support (MongoDB, Redis, Elasticsearch, Sphinx), template engines (Twig, Smarty), and developer tools (Gii, Debug, Shell).

    Official Extensions for Yii 2.0

    • yiisoft/yii2-apidoc: API documentation generator.
    • yiisoft/yii2-authclient: OAuth2 clients (Facebook, GitHub, etc.).
    • yiisoft/yii2-bootstrap: Bootstrap component widgets.
    • yiisoft/yii2-debug: Debugging toolbar and standalone debug pages.
    • yiisoft/yii2-elasticsearch: Elasticsearch support and Active Record implementation.
    • yiisoft/yii2-faker: Fake data generation using Faker.
    • yiisoft/yii2-gii: Web-based code generator for models, forms, CRUD, etc.
    • yiisoft/yii2-httpclient: HTTP client.
    • yiisoft/yii2-imagine: Image manipulation via Imagine.
    • yiisoft/yii2-jui: jQuery UI widget encapsulation.
    • yiisoft/yii2-mongodb: MongoDB support including Active Record and migrations.
    • yiisoft/yii2-queue: Asynchronous task queues (DB, Redis, RabbitMQ, AMQP, Beanstalk, Gearman).
    • yiisoft/yii2-redis: Redis support including Active Record and caching.
    • yiisoft/yii2-shell: Interactive shell based on psysh.
    • yiisoft/yii2-smarty: Smarty template engine.
    • yiisoft/yii2-sphinx: Sphinx search support and Active Record.
    • yiisoft/yii2-symfonymailer: Email sending via Symfony Mailer.
    • yiisoft/yii2-twig: Twig template engine.

    Extensions for Yii 2.1+

    The following are included in the Yii 2.0 core and do not need separate installation for 2.0 users, but are available as extensions for 2.1+:

    • yiisoft/yii2-captcha: CAPTCHA support.
    • yiisoft/yii2-jquery: jQuery support.
    • yiisoft/yii2-maskedinput: jQuery Input Mask plugin widgets.
    • yiisoft/yii2-mssql: MSSQL support.
    • yiisoft/yii2-oracle: Oracle support.
    • yiisoft/yii2-rest: REST API support.
  2. Get started with Yii 2.0 (Ukrainian Guide Overview)

    master

    This document serves as the table of contents for the complete Ukrainian language guide for Yii 2.0. It organizes learning paths into logical sections such as Installation, Application Structure, Request Handling, Core Concepts, Database Interaction, User Input, Data Display, Security, Caching, and RESTful Web Services.

    Key learning paths include:

    • First Steps: Installation, workflow, 'Hello World', forms, and database basics.
    • Application Structure: Understanding entry scripts, applications, components, controllers, and models.
    • Core Concepts: Components, properties, events, behaviors, configurations, aliases, and autoloading.
    • Database Work: DAO, Query Builder, Active Record, and Migrations.
    • RESTful Services: Quick start, resources, controllers, routing, and authentication.
    • Developer Tools: Gii (code generation) and the Debugger/Debug Panel.
  3. Core Yii 2 Extensions Overview

    master

    Yii provides several core extensions maintained by the official development team. These extensions add specialized functionality to your application, such as database support, UI widgets, and API tools. Most are available on Packagist and can be installed via Composer.

    Key core extensions include:

    • API & Documentation: yiisoft/yii2-apidoc (API documentation generator).
    • Authentication: yiisoft/yii2-authclient (OAuth2 clients like Facebook and GitHub).
    • UI & Frontend: yiisoft/yii2-bootstrap (Bootstrap widgets), yiisoft/yii2-jui (jQuery UI widgets), and yiisoft/yii2-imagine (image manipulation).
    • Database & Search: yiisoft/yii2-elasticsearch (Elasticsearch support), yiisoft/yii2-mongodb (MongoDB support), yiisoft/yii2-redis (Redis support), and yiisoft/yii2-sphinx (Sphinx support). These often include Active Record implementations.
    • Development Tools: yiisoft/yii2-debug (debug toolbar and info pages), yiisoft/yii2-faker (data generation), and yiisoft/yii2-gii (web-based code generator for models, CRUD, etc.).
    • Templating: yiisoft/yii2-smarty (Smarty engine) and yiisoft/yii2-twig (Twig engine).
    • Utilities: yiisoft/yii2-httpclient (HTTP client) and yiisoft/yii2-swiftmailer (email sending).
  4. Get started with Yii 2.0

    master

    The Yii 2.0 guide provides a comprehensive roadmap for developers. To begin building an application, follow these primary tracks:

    1. Initial Setup: Learn prerequisites, installation methods, and how to run your first 'Hello World' application.
    2. Application Structure: Understand the roles of entry scripts, controllers, models, views, modules, widgets, and assets.
    3. Request Handling: Master the lifecycle of a request, including bootstrapping, routing, sessions, cookies, and error handling.
    4. Core Concepts: Familiarize yourself with components, properties, events, behaviors, and the Dependency Injection (DI) container.
    5. Database Interaction: Use DAO (Data Access Objects), Query Builder, Active Record ORM, and Migrations to manage data.
    6. User Input & Output: Implement forms with validation, handle file uploads, and display data using pagination, sorting, and data providers.
    7. Security: Implement authentication, authorization, password hashing, and cryptography.
    8. RESTful Web Services: Build APIs using Yii's built-in REST support, including resource management, routing, and rate limiting.
    9. Testing: Set up environments for unit, functional, and acceptance testing using fixtures.
  5. Explore official Yii 2 core extensions

    master

    Yii provides a variety of official extensions maintained by the development team. These extensions add specialized functionality such as database support, UI components, and utility tools. Most are available on Packagist and can be installed via Composer.

    Key Core Extensions

    Database & Search

    • yiisoft/yii2-elasticsearch: Support for Elasticsearch, including Active Record implementation.
    • yiisoft/yii2-mongodb: Support for MongoDB (queries, Active Record, migrations, caching).
    • yiisoft/yii2-redis: Support for Redis (queries, Active Record, caching).
    • yiisoft/yii2-sphinx: Support for Sphinx (queries, Active Record).
    • yiisoft/yii2-mssql: Support for MSSQL.
    • yiisoft/yii2-oracle: Support for Oracle.

    UI & Frontend

    • yiisoft/yii2-bootstrap: Bootstrap component encapsulation.
    • yiisoft/yii2-jui: JQuery UI interaction and widget encapsulation.
    • yiisoft/yii2-imagine: Image manipulation based on Imagine.
    • yiisoft/yii2-smarty: Smarty template engine support.
    • yiisoft/yii2-twig: Twig template engine support.

    Development & Debugging

    • yiisoft/yii2-debug: Debugging support with a debug toolbar and standalone debug pages.
    • yiisoft/yii2-gii: Web-based code generator for models, forms, modules, and CRUD.
    • yiisoft/yii2-faker: Data generation using Faker.
    • yiisoft/yii2-shell: Command-line shell interpreter based on psysh.
    • yiisoft/yii2-apidoc: High-performance API documentation generator.

    Utilities & Integration

    • yiisoft/yii2-authclient: Common authentication clients (e.g., Facebook, GitHub OAuth2).
    • yiisoft/yii2-httpclient: HTTP client for making requests.
    • yiisoft/yii2-queue: Asynchronous task execution (supports DB, Redis, RabbitMQ, AMQP, Beanstalk, and Gearman).
    • yiisoft/yii2-swiftmailer: Email sending via SwiftMailer.
  6. Understand the Basic Application Template functionality

    master

    The Yii2 Basic Application Template comes with built-in functionality to help you get started. It includes several pre-configured pages:

    • Homepage: Accessible via https://hostname/index.php.
    • About page: A static informational page.
    • Contact page: Includes a form that allows users to contact you via email.
    • Login page: A form for user authentication. For example, logging in as admin/admin will change the 'Login' menu item to 'Logout'.

    All pages share a common header (containing the main menu) and footer.

    Additionally, the template includes:

    • Debugger Tool: A toolbar at the bottom of the browser window used for debugging, displaying log messages, response statuses, and database queries.
    • Console Script: A script named yii located in the application root used for running background tasks or maintenance commands.
  7. Native Yii 2 Extensions Overview

    master

    Yii provides several core extensions developed and maintained by the Yii team. These extensions are registered on Packagist and can be installed via Composer. They provide specialized functionality such as database support, UI widgets, and utility tools.

    Core Extensions List:

    • API Documentation: yiisoft/yii2-apidoc (extensible, high-performance API documentation generator).
    • Authentication: yiisoft/yii2-authclient (common client authenticators like Facebook and GitHub OAuth2).
    • UI Frameworks:
      • yiisoft/yii2-bootstrap (widgets encapsulating Bootstrap components/plugins).
      • yiisoft/yii2-jui (widgets encapsulating jQuery UI interactions).
    • Debugging: yiisoft/yii2-debug (adds a debug toolbar to the bottom of pages and provides detailed debug info pages).
    • Search & Databases:
      • yiisoft/yii2-elasticsearch (Elasticsearch support including Active Record implementation).
      • yiisoft/yii2-mongodb (MongoDB support including Active Record, migrations, and cache).
      • yiisoft/yii2-redis (Redis support including Active Record and cache).
      • yiisoft/yii2-sphinx (Sphinx support including Active Record).
    • Utilities:
      • yiisoft/yii2-faker (Faker support for generating dummy data).
      • yiisoft/yii2-httpclient (HTTP client).
      • yiisoft/yii2-imagine (Image manipulation based on Imagine).
      • yiisoft/yii2-swiftmailer (Email sending based on SwiftMailer).
    • Code Generation: yiisoft/yii2-gii (Web-based code generator for models, forms, modules, CRUD, etc.).
    • Template Engines:
      • yiisoft/yii2-smarty (Smarty template engine).
      • yiisoft/yii2-twig (Twig template engine).
  8. What is Active Record in Yii 2

    master

    Active Record provides an object-oriented interface for accessing and manipulating database data. In this pattern:

    • An Active Record class is associated with a database table.
    • An Active Record instance corresponds to a single row in that table.
    • An attribute of an instance represents the value of a specific column in that row.

    Instead of writing raw SQL, you interact with attributes and methods to perform CRUD operations. Yii supports various relational databases (MySQL, PostgreSQL, SQLite, MS SQL, Oracle, CUBRID, Sphinx, ElasticSearch) and NoSQL databases (Redis, MongoDB) via specific extensions.

  9. How to create a content-enclosing widget

    master

    To create a widget that wraps content (using begin() and end()), you must use PHP's output buffering within the widget class:

    1. In init(), call ob_start() to start the output buffer.
    2. In run(), call ob_get_clean() to capture the buffered content (the content placed between begin() and end() in the view) and process it (e.g., encoding it).

    When a user calls Widget::begin(), a new instance is created and init() is called. When Widget::end() is called, run() is executed and its result is echoed.

    namespace app\components;
    
    use yii\base\Widget;
    use yii\helpers\Html;
    
    class HelloWidget extends Widget
    {
        public function init()
        {
            parent::init();
            ob_start();
        }
    
        public function run()
        {
            $content = ob_get_clean();
            return Html::encode($content);
        }
    }
  10. Core Concepts: Components, Events, and Behaviors

    master

    Yii 2.0 is built on several fundamental abstractions that allow for highly flexible and extensible code:

    • Components: Objects that provide basic functionality and can be configured.
    • Properties: Accessing object attributes via getter/setter methods.
    • Events: A mechanism to trigger and respond to specific occurrences in the application lifecycle.
    • Behaviors: A way to inject new properties and methods into a component dynamically.
    • Service Locator: A registry for accessing application components.
    • Dependency Injection (DI) Container: Managing object creation and dependency resolution.
  11. How the bootstrap property works

    master

    The bootstrap property specifies an array of components that should be loaded during the application's bootstrapping process. This is useful for initializing modules or components that need to perform fine-tuning (like URL rule configuration) before the application handles requests.

    Each element in the bootstrap array can be:

    • A component ID.
    • A module ID.
    • A class name.
    • A configuration array.
    • An anonymous function that creates and returns a component.

    Important Notes:

    • If a module ID matches an application component ID, the application component will be used. To force the use of a module, use an anonymous function: function () { return Yii::$app->getModule('user'); }.
    • If a component implements yii\base\BootstrapInterface, its bootstrap() method will be called during the process.
    • Performance Warning: Adding too many components to bootstrap will decrease application performance because they are loaded for every single request.

    Example configuration:

    [
        'bootstrap' => [
            'demo', // Component ID
            'app\components\Profiler', // Class name
            [
                'class' => 'app\components\Profiler',
                'level' => 3,
            ], // Configuration array
            function () {
                return new app\components\Profiler();
            }, // Anonymous function
        ],
    ]
    [
        'bootstrap' => [
            'demo',
            'app\components\Profiler',
            [
                'class' => 'app\components\Profiler',
                'level' => 3,
            ],
            function () {
                return new app\components\Profiler();
            }
        ],
    ]
  12. Create Dynamic Asset Bundles

    master

    Asset bundles are standard PHP classes, allowing you to implement custom logic to adjust parameters dynamically. A common use case is loading different internationalization (i18n) files based on the application language.

    You can achieve this by overriding the init() method within your AssetBundle class.

    Note: While dynamic adjustment is supported, it is considered a bad practice to modify a bundle instance after registration (e.g., $bundle->js[] = ...) as it can lead to unexpected side effects. Prefer overriding init() instead.

    namespace app\assets;
    
    use yii\web\AssetBundle;
    use Yii;
    
    class SophisticatedAssetBundle extends AssetBundle
    {
        public $sourcePath = '/path/to/sophisticated/src';
        public $js = [
            'sophisticated.js' // file, which is always used
        ];
    
        public function init()
        {
            parent::init();
            $this->js[] = 'i18n/' . Yii::$app->language . '.js'; // dynamic file added
        }
    }