Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Yii2 Laravel Package

yiisoft/yii2

Yii 2 is a fast, secure, and extensible PHP framework for building modern web apps. It includes powerful MVC architecture, ORM (ActiveRecord), caching, RBAC, REST APIs, code generation, and excellent performance for large-scale projects.

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer create-project --prefer-dist yiisoft/yii2-app-basic basic
    

    Navigate to the project directory and run:

    composer install
    
  2. First Use Case: Basic CRUD

    • Scaffold a model, view, and controller using Gii (Yii’s built-in code generator):
      • Enable Gii in config/web.php:
        'enableGii' => true,
        
      • Access http://your-app.dev/gii and generate a CRUD for a model (e.g., Post).
  3. Key Files to Review

    • config/web.php: Core application configuration (routes, middleware, components).
    • models/: Business logic and database interactions.
    • controllers/: HTTP request handling.
    • views/: Presentation layer (Twig or PHP templates).

Implementation Patterns

Core Workflows

  1. MVC Integration

    • Model: Extend yii\base\Model or yii\db\ActiveRecord for database interactions.
      namespace app\models;
      use yii\db\ActiveRecord;
      
      class Post extends ActiveRecord { /* ... */ }
      
    • Controller: Use dependency injection for services/models.
      public function actionView($id) {
          $post = Post::findOne($id);
          return $this->render('view', ['post' => $post]);
      }
      
    • View: Leverage Yii’s widgets and helpers (e.g., GridView, Url::to()).
  2. Database Operations

    • ActiveRecord: ORM for CRUD.
      $post = new Post();
      $post->title = 'Hello Yii';
      $post->save();
      
    • Query Builder: Complex queries.
      $posts = Post::find()->where(['status' => 1])->all();
      
  3. Routing and URL Handling

    • Define routes in config/web.php:
      'urlManager' => [
          'enablePrettyUrl' => true,
          'showScriptName' => false,
          'rules' => [
              'posts/<id:\d+>' => 'post/view',
          ],
      ],
      
    • Use Url::to() in views/controllers for dynamic links.
  4. Middleware and Filters

    • Apply behaviors to controllers:
      public function behaviors() {
          return [
              'access' => ['class' => \yii\filters\AccessControl::class],
          ];
      }
      
    • Use beforeAction for pre-processing:
      public function beforeAction($action) {
          if ($action->id === 'index' && !$this->user->isGuest) {
              return $this->redirect(['site/index']);
          }
          return parent::beforeAction($action);
      }
      
  5. Asset Management

    • Bundle CSS/JS in AssetBundle:
      namespace app\assets;
      use yii\web\AssetBundle;
      
      class AppAsset extends AssetBundle {
          public $basePath = '@webroot';
          public $baseUrl = '@web';
          public $css = ['css/site.css'];
          public $js = ['js/site.js'];
      }
      
    • Register in layouts/views:
      AppAsset::register($this);
      
  6. Authentication and Authorization

    • Use yii\web\User for sessions/auth:
      if (Yii::$app->user->isGuest) {
          return $this->goHome();
      }
      
    • RBAC via yii\rbac\PhpManager:
      $auth = Yii::$app->authManager;
      $auth->addRole('admin');
      $auth->addPermission('createPost');
      $auth->addChild('admin', 'createPost');
      
  7. API Development

    • RESTful controllers with yii\rest\ActiveController:
      namespace app\controllers;
      use yii\rest\ActiveController;
      
      class PostController extends ActiveController {
          public $modelClass = 'app\models\Post';
      }
      
    • Enable in config/web.php:
      'components' => [
          'urlManager' => [
              'enablePrettyUrl' => true,
              'rules' => [
                  'api/v1/posts' => 'post/index',
              ],
          ],
      ],
      

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Routes

    • Yii routes are case-sensitive by default. Use lowercaseUrl in UrlManager if needed:
      'urlManager' => [
          'lowercaseUrl' => true,
      ],
      
  2. Session Configuration

    • Ensure session component is properly configured in config/web.php:
      'components' => [
          'session' => [
              'class' => 'yii\web\CookieSession',
              'timeout' => 120,
          ],
      ],
      
    • For custom storage (e.g., Redis), use:
      'session' => [
          'class' => 'yii\redis\Session',
          'timeout' => 120,
      ],
      
  3. ActiveRecord Caching

    • Cache queries to avoid N+1 problems:
      Yii::$app->db->enableQueryCache = true;
      Yii::$app->cache = [
          'class' => 'yii\caching\FileCache',
      ];
      
  4. Gii Security

    • Restrict Gii access in production by IP or user role:
      'modules' => [
          'gii' => [
              'class' => 'yii\gii\Module',
              'allowedIPs' => ['127.0.0.1', '::1'],
          ],
      ],
      
  5. Event Handling

    • Override events carefully to avoid infinite loops:
      public function init() {
          parent::init();
          $this->on('eventName', function($event) {
              // Handle event
          });
      }
      
  6. Translation Quirks

    • Ensure sourceLanguage and translations are set in i18n:
      'i18n' => [
          'sourceLanguage' => 'en-US',
          'translations' => [
              'app*' => [
                  'class' => 'yii\i18n\PhpMessageSource',
                  'basePath' => '@app/messages',
              ],
          ],
      ],
      
    • Use Yii::t() for translations:
      Yii::t('app', 'Hello {name}', ['name' => 'World']);
      
  7. Asset Publishing

    • Publish assets before using them in views:
      Yii::$app->assetManager->publish($assetBundle);
      
    • Debug missing assets with:
      php yii asset/index
      

Debugging Tips

  1. Error Handling

    • Enable debug mode in config/web.php:
      'components' => [
          'errorHandler' => [
              'errorAction' => 'site/error',
          ],
      ],
      
    • Use Yii::error() and Yii::warning() for logging.
  2. Logging

    • Configure log component:
      'log' => [
          'traceLevel' => YII_DEBUG ? 3 : 0,
          'targets' => [
              [
                  'class' => 'yii\log\FileTarget',
                  'levels' => ['error', 'warning'],
              ],
          ],
      ],
      
  3. Database Debugging

    • Enable query logging:
      'components' => [
          'db' => [
              'enableProfiling' => true,
              'enableLogging' => true,
          ],
      ],
      
    • View logs via Yii::$app->db->getLogger()->logs.
  4. Common Issues

    • 404 Errors: Verify urlManager rules and web.php base URL.
    • CSRF Tokens: Ensure Csrf::validate() is called in forms.
    • Session Expiry: Check session component timeout and cookie settings.

Extension Points

  1. Custom Components

    • Extend core components (e.g., yii\db\Connection) for reusable logic:
      namespace app\components;
      use yii\db\Connection;
      
      class CustomDb extends Connection {
          public function customQuery() { /* ... */ }
      }
      
    • Register in config/web.php:
      'components' => [
          'db' => ['class' => 'app\components\CustomDb'],
      ],
      
  2. Behaviors

    • Attach behaviors to models/controllers for reusable logic:
      public function behaviors() {
          return [
              'timestamp' => [
                  'class' => 'yii\
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport