I'm using the basic template for Yii2. I created the project and uploaded it to github so other devs can clone and start contributing.
After cloning and running composer install, I'm getting this error when I try to run yii migrate.
λ php yii migrate
Yii Migration Tool (based on Yii v2.0.8)
Total 1 new migration to be applied:
m160704_071418_user_table
Apply the above migration? (yes|no) [no]:yes
*** applying m160704_071418_user_table
PHP Fatal Error 'yii\base\ErrorException' with message 'Class 'm160704_071418_user_table' not found'
in C:\wamp\www\miespacio\vendor\yiisoft\yii2\console\controllers\MigrateController.php:170
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}
My question is: Is there any steps I'm missing to make this work? Any help would be appreciated, thanks.
Potentially useful information: I can create new migrations and run them just fine after cloning. The problem is running existing migrations.
You should create migration by yii migrate/create <migration-name> command. And don't change file name or class name of migrations.
Example: create migration add test table
yii migrate/create create_test_table
After run that command, you will have a php file in #app/migrations
Filename: m160704_110735_create_test_table.php
Code generator:
<?php
use yii\db\Migration;
/**
* Handles the creation for table `test_table`.
*/
class m160704_110735_create_test_table extends Migration
{
/**
* #inheritdoc
*/
public function up()
{
$this->createTable('test_table', [
'id' => $this->primaryKey(),
]);
}
/**
* #inheritdoc
*/
public function down()
{
$this->dropTable('test_table');
}
}
Remember: don't change filename or class name.
Goodluck and have fun!
Related
I would like to do some unit-testing in Symfony and am attempting to test something that already works, like this:
<?php namespace App\Tests\Api\Controller;
use Symfony\Component\HttpFoundation\Request;
use App\Controller\Admin\ProductAdminController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Class ProductsAdminControllerTest
* #package App\Tests\Api\Controller
*/
class ProductsAdminControllerTest extends WebTestCase
{
protected function setUp()
{
$kernel = static::createKernel();
$kernel->boot();
static::$container = $kernel->getContainer();
/*$this->_em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
$this->_em->beginTransaction();*/
}
public function testSearchProductsEmpty()
{
$request = new Request([], [
"product_name" => ""
]);
$controller = new ProductsAdminController();
$controller->setContainer(static::$container);
$controller->getProducts($request);
//$products = json_decode($controller->getProducts($request));
$this->assertEquals(1, 1);
}
}
Of course this will be modified after I overcome my current problem, which is that no matter what I do, I get the error of
Doctrine\DBAL\Exception\ConnectionException: An exception occurred in
driver: SQLSTATE[HY000] [1045] Access denied for user
'db_user'#'localhost' (using password: YES)
Of course the database where my dev env is connecting has different credentials and I would like to ensure that my unit test is using the same credentials. How to achieve that?
If you want to using different connection parameters for different environment, you can override configuration by creating file in config/packages/{env}/doctrine.yaml
For testing you can create config/packages/test/doctrine.yaml
doctrine:
dbal:
# configure these for your database server
url: 'mysql://db_user4test:db_password4test#host4test:3306/dbname4test'
phpunit will use this configuration.
otherwise you can create a .env.test and override configuration (Customizing Database URL / Environment Variables)
[EDIT] Another way as suggested by #LajosArpad is to add in phpunit.xml.dist:
<env name="DATABASE_URL" value="mysql://db_user4test:db_password4test#host4test:3306/dbname4test" />
See Changing Database Settings for Functional Tests
I am working on a requirement of where I have to include all common methods like pagination, etc. which were used in my views into all my views. For this purpose I thought helper file is useful and created helper file in common\helpers\ directory with name Common as helper file name. I am facing difficulty in using this helper file in my view file.
I have included this helper file in my view as
use common\helpers\Common;
When I open the page I am getting error as "Class 'common\helpers\Common' not found"
My helper file: Common.php
namespace common\helpers;
class Common
{
protected $_file;
protected $_data = array();
public function __construct($file)
{
$this->_file = $file;
}
public static function getCommonHtml($id=NULL)
{
----
----
}
-----
--- Some other methods---
-----
}
I googled for this & got few solutions but they never worked.
You need to declare your new namespace in your composer.json:
"autoload": {
"psr-4": {
...
"common\\": "common/"
}
},
And the run:
composer dump-autoload
Alternatively you could declare alias for new namespace, so Yii autoloader will handle it (like in advanced template):
Yii::setAlias('#common', dirname(__DIR__))
But Yii autoloader will be dropped in Yii 2.1, so I would stick to composer-way (or do both - alias may be useful not only for autoloading).
Unloading issue
I'm trying to create fixtures in Yii2 to be able to fill my tables with some test data. I'm not using Codeception yet. I'm following the Yii2 guide on fixtures. The first table is the User table:
namespace tests\unit\fixtures;
use yii\test\ActiveFixture;
/**
* User fixture
*/
class UserFixture extends ActiveFixture
{
public $modelClass = 'common\models\User';
}
This one works when I ssh into Vagrant and load the fixture, but the entries are still there after I do an unload. According to the terminal output the fixture was successfully unloaded. What am I missing here? Should this work out of the box or should you create your own unload function?
Edit:
What did help was adding this to the User fixture:
public function unload(){
parent::unload();
$this->resetTable();
}
I would expect this to be present in unload anyhow, but I have read the (very slow) discussion in the link posted below. I don't know if the parent::unload() line was necessary, it worked without the line, but BaseActiveFixture defines it and empties $this->data and $this->_models.
Depends issue
My second fixture depends on the User fixture:
namespace tests\unit\fixtures;
use yii\test\ActiveFixture;
/**
* User Libraries fixture
*/
class UserLibrariesFixture extends ActiveFixture
{
public $modelClass = 'common\models\UserLibraries';
// Dependencies
public $depends = [
'tests\unit\fixtures\UserFixture',
];
}
This one also loads correctly according to the terminal, but the UserLibraries table remains empty. It doesn't say it will load the dependencies, but I don't know if it should say that it will.
I've kept the data files as simple as possible and the correct data appears in the User table. I only added data for the required fields for the UserLibraries table, so I don't know if that could be an issue. Is there a log file that I can check for entries regarding the fixtures?
Edit:
The UserLibraries fixture is now able to create data in the User table (but not the UserLibraries table), so disabling the foreign key check works for fixtures with dependencies. That makes me think there is an error in my data file for the UserLibraries. To check that I need a log file.
Edit2:
Fixture loading issue solution
The fixtures would not load because of an underscore in the table names. The table names userLibraries and user_libraries will result in model, controller and view files with identical file names when created with Gii. With the camelcase name table I am able to load fixtures.
Unloading fixtures is a question "under discussion" (see here). But this is my mysql workaround for it (I also commented there) and should be added to each fixture model that has some dependant table:
<?php
namespace tests\codeception\common\fixtures;
use yii\test\ActiveFixture;
class VariationFixture extends ActiveFixture
{
public $modelClass = 'common\models\Variation';
public function beforeLoad() {
parent::beforeLoad();
$this->db->createCommand()->setSql('SET FOREIGN_KEY_CHECKS = 0')->execute();
}
public function afterLoad() {
parent::afterLoad();
$this->db->createCommand()->setSql('SET FOREIGN_KEY_CHECKS = 1')->execute();
}
}
As to the loading, using codeception you can use /tests/codeception/common/_support/FixtureHelper::fixtures() to define the fixtures you want to be loaded before each test case:
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '#tests/codeception/common/fixtures/data/init_login.php',
],
'room' => [
'class' => RoomFixture::className(),
'dataFile' => '#tests/codeception/common/fixtures/company/data/room.php',
],
...
];
}
I want to use this php library with namespaced classes in my Symfony 1.4 project: https://github.com/donquixote/cellbrush.
I'm not quite familiar with the namespaces concept. So when i fisrt try the to use the main class of this library, according to its docs, i just did:
$table = \Donquixote\Cellbrush\Table\Table::create();
And i got this fatal error:
Fatal error: Class 'Donquixote\Cellbrush\Table\Table' not found in D:\SF_ROOT_DIR\apps\frontend\modules\home\actions\actions.class.php
So i searched for a solution, and supposedly there is one: stackoverflow sol 1, stackoverflow sol 1 eg, but when i try to implement it i still get the above error.
My case:
Directories and files of interest:
D:\SF_ROOT_DIR\lib\autoload\sfClassLoader.class.php
D:\SF_ROOT_DIR\lib\vendor\ClassLoader (contains:
https://github.com/symfony/ClassLoader/tree/2.6)
D:\SF_ROOT_DIR\lib\vendor\cellbrush-1.0 (contains:
https://github.com/donquixote/cellbrush.)
Code:
SF_ROOT_DIR/config/ProjectConfiguration.class.php
require_once dirname(__FILE__).'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
require_once dirname(__FILE__) . '/../lib/autoload/sfClassLoader.class.php';
use Symfony\Component\ClassLoader\UniversalClassLoader;
use Symfony\Component\ClassLoader\ApcUniversalClassLoader;
sfCoreAutoload::register();
class ProjectConfiguration extends sfProjectConfiguration
{
public function setup()
{
$this->namespacesClassLoader();
$this->enableAllPluginsExcept('sfPropelPlugin');
}
public function namespacesClassLoader() {
if (extension_loaded('apc')) {
$loader = new ApcUniversalClassLoader('S2A');
} else {
$loader = new UniversalClassLoader();
}
$loader->registerNamespaces(array(
'Donquixote' => __DIR__ . '/../lib/vendor/cellbrush-1.0/src/Table'));
$loader->register();
}
}
actions.class.php
$table = \Donquixote\Cellbrush\Table\Table::create();
Thanks.
Use composer and its autoloading.
Execute:
composer require donquixote/cellbrush
Now the library is installed in vendor directory and autoloader is generated, you just need to include it. Add this line to the top of config/ProjectConfiguration.class.php:
require_once dirname(__FILE__).'/../vendor/autoload.php';
I have an issue which I could not find answer for across the web.
I am using CodeFirst EF 4.3.1 Migrations with MySQL.
My MySQL provider is Devart.
After running Add-Migration against an existing database, I got the following code:
public partial class ChangeSet_1231 : DbMigration
{
public override void Up()
{
RenameColumn(table: "RW_TTaskInstanceProperties", name: "TaskInstance_TaskInstanceId", newName: "TaskInstanceId");
}
public override void Down()
{
RenameColumn(table: "RW_TTaskInstanceProperties", name: "TaskInstanceId", newName: "TaskInstance_TaskInstanceId");
}
}
Running Update-Database results in the following error:
PM> Update-Database -verbose –startupprojectname "RTDataAccess"
Using NuGet project 'RTDataAccess'.
Target database is: 'rsruntime' (DataSource: localhost, Provider: Devart.Data.MySql, Origin: Explicit).
Applying explicit migrations: [201205311312361_ChangeSet_1231].
Applying explicit migration: 201205311312361_ChangeSet_1231.
ALTER TABLE RW_TTaskInstanceProperties RENAME COLUMN TaskInstance_TaskInstanceId TO TaskInstanceId
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COLUMN TaskInstance_TaskInstanceId TO TaskInstanceId' at line 2
From looking at the error details I see that the RenameColumn is translated to a MsSql command, rather than MySql command, so no wonder it reports about a syntax error.
Any ideas how to solve it?
I know I can use Update-Database -script, then edit the script to fit MySql and run it, but I prefer to make the Update-Database command work...
Thanks.
In response to Ladislav's question:
Yes, I registered the Devart's SQL generator for MySQL Migrations.
My Configuration class looks like that:
using Devart.Data.MySql.Entity.Configuration;
using Devart.Data.MySql.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<RTDataAccess.RTContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MySqlEntityProviderConfig.Instance.Workarounds.IgnoreSchemaName = true;
var connectionInfo = MySqlConnectionInfo.CreateConnection("Server=xxxx;Port=yyyy;Database=rsruntime;Uid=zzzz;Pwd=wwww;charset=utf8;");
this.TargetDatabase = connectionInfo;
this.SetSqlGenerator(connectionInfo.GetInvariantName(), new MySqlEntityMigrationSqlGenerator());
}
protected override void Seed(RTDataAccess.RTContext context)
{
}
}
The issue was fixed by Devart.
Details at the following links:
http://forums.devart.com/viewtopic.php?f=2&t=24250
http://www.devart.com/dotconnect/mysql/download.html