1

Calling all Yii and Composer masters! I need your help :)

I'm new to Yii and I'm creating a composer plug-in for a Yii2 project and it needs the Dependency Injection Container to make this work. To summarize what my plug-in does is that once the plug-in is added to the project via composer, I want to create a database table.

I've already created a composer-plugin that doesn't do anything yet and can be added to the project's dependencies successfully. It has the basic files needed for a composer plug-in to be installed (like composer.json, and Plugin.php). When I added bits and pieces of code, I encountered a couple of problems.

One of my problems is that I can't reach the classes in Yii. I have this error when I try to use 'Yii::$app':

PHP Fatal error: Class 'Yii' not found in ...

So I guess 'use Yii;' doesn't work(?)

Another problem is that when I apply the snippet needed that's in Yii2's documentation, I get this:

PHP Fatal error: Uncaught TypeError: Argument 1 passed to Experiment\Plugin::__construct() must be an instance of yii\db\Connection, none given

Am I doing it wrong or did I miss anything? I would like to know how to resolve this, and the right way of doing Yii composer plug-ins. How do you connect a composer plug-in to the Yii database(any kind of db)?

The following code might be of help:

composer.json

{
    "name": "rencamp/experiment-component",
    "description": "This is a test package.",
    "type": "composer-plugin",
    "require": {
        "yiisoft/yii2": "^2.0",
        "composer-plugin-api": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "Experiment\\": "src"
        }
    },
    "extra": {
        "class": "Experiment\\Plugin"
    },
    "minimum-stability": "dev"
}

Plugin.php(this is inside the folder 'src')

<?php
namespace Experiment;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Package\Link;
use Composer\Plugin\PluginInterface;

use Yii;
use yii\base\Component;
use yii\base\Object;
use yii\db\Connection;

class Plugin extends Object implements PluginInterface
{

  public function __construct(Connection $db, $config = [])
  {
      $this->db = $db;
      parent::__construct($config);
  }

    /**
     * @param Composer $composer
     * @param IOInterface $io
     */
    public function activate(Composer $composer, IOInterface $io)
    {
        print_r("\n\rActivated.\n\r");
    }

    private function createTable()
    {
      print_r("create table here...\n\r");
    }
}

And by the way, this is in packagist and in github.

Thank you so much for your help!

Ren Camp
  • 430
  • 7
  • 14

0 Answers0