Yii config file override - php

I have a Yii project with a main.php config file and dev.php config file which "inherits" from it. The files are as follows:
main.php:
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath' => dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..',
'name' => 'FeedStreem',
// preloading 'log' component
'preload' => array( 'log' ),
// autoloading model and component classes
'import' => array(
'application.models.*',
'application.components.*',
'application.controllers.*',
),
// application components
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=remote.host.com;dbname=dbnamehere',
'emulatePrepare' => true,
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
/*'enableProfiling' => true*/
),
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
),
'authManager' => array(
'class' => 'CDbAuthManager',
'connectionID' => 'db'
),
'urlManager' => array(
// omitted
),
'errorHandler' => array(
// use 'site/error' action to display errors
'errorAction' => 'site/error',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'trace, info, error, warning',
),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params' => array(
// this is used in contact page
'adminEmail' => 'webmaster#example.com',
),
);
dev.php:
<?php
return CMap::mergeArray(
require(dirname( __FILE__ ) . '/main.php'),
array(
'modules' => array(
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'SECRET',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters' => array( '127.0.0.1', '::1' ),
),
),
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=dbname2',
'emulatePrepare' => true,
'username' => 'username2',
'password' => 'password2',
'charset' => 'utf8',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'trace, info, error, warning',
),
// uncomment the following to show log messages on web pages
array(
'class' => 'CWebLogRoute',
),
),
),
),
)
);
However, when I use dev.php locally, I get the following error:
Warning: PDO::__construct() [pdo.--construct]: [2002] No connection could be made because the target machine actively (trying to connect via tcp://remote.host.com:3306) in C:\web_workspace\lib\yii\framework\db\CDbConnection.php on line 405
Which tells me the dev.php did not overwrite that 'db' config option. How can I make a config file that inherits from main.php but can overwrite options when I merge it?

As far as i see from source code it should overwrite your config:
public static function mergeArray($a,$b)
{
foreach($b as $k=>$v)
{
if(is_integer($k))
isset($a[$k]) ? $a[]=$v : $a[$k]=$v;
else if(is_array($v) && isset($a[$k]) && is_array($a[$k]))
$a[$k]=self::mergeArray($a[$k],$v);
else
$a[$k]=$v;
}
return $a;
}
Source: http://code.google.com/p/yii/source/browse/tags/1.1.8/framework/collections/CMap.php
Also official documentation says so:
If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive).
Source: http://www.yiiframework.com/doc/api/1.1/CMap#mergeArray-detail
Try to determine the problem via print_r the result array and look at it inner structure. I think the problem is here.

If your project involves (or will involve) more than 1 developer, server, or customized deployment/test you have to watch out for VCS problems. For us we found it best to import a separate db.php file in config/main.php:
'db'=>require(dirname(__FILE__).'/db.php'),
The db.php file is a copy of (or symbolic link to) either db-test.php or db-deploy.php and is ignored by our VCS, while the various db-*.php files created for individual users continue to be tracked by the VCS:
bzr add protected/config/db-*.php
bzr ignore protected/config/db.php
This allows individual developers to run the system on their home machine connected to localhost databases while maintaining the deployed system's link to the central db.

I apologize if Yii has evolved much since I tested it out, but as I recall, you need to kind of work around this issue. Here is a link which outlines a few methods of doing so. It may be worth checking around to see if things have improved.
Blog article on environment dependent configuration
If you work with a dev, staging, and production environment which are all separate and maintained via git/svn/something else, I find it's easiest to ignore certain config files with frameworks that ignore environment settings. You have to make changes manually across these files at times, but this isn't a hardship as config files tend to remain similar once an app or website is established. This way you can tailor your settings for your environment for better debugging and testing on dev/staging, and otherwise better performance and no debugging on production.

How are you determining which config file to use? With a switch statement like Steve linked to?
I use an if statement in my index.php to decide which config file to use based on the server environment (as mentioned in the article Steve linked). It seems to work fine for me.
Also remember that if you are running a console application, you need to tell it to use the right conig file in protected/yiic.php also (just like in index.php).
Another thing that may be happening is CMap::mergeArray might not be merging like you want. Again, it works for me, but perhaps when the arrays are merged it is overwriting the wrong DB config string (it's choosing the wrong one)?
One way to fix this would be to NOT have the DB creds in the main.php config file, and just have them in each inheriting file. So you will need an inheriting file for each environment, and no environment will run directly off of the main.php file. This way when the arrays are merged you will always have the right DB connection string.
Good luck!

I have 2 configuration files (development and production). May be you can try my configuration.
main.php
return array(
'name' => 'My Application',
'language' => 'id',
'charset' => 'utf-8',
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
// gii module
'modules' => array(
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'admin'
),
),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
// preloading 'log' component
'preload' => array('log'),
'defaultController' => 'site',
// application components
'components' => array(
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
'loginUrl' => array('user/login'),
),
'errorHandler' => array(
// use 'site/error' action to display errors
'errorAction' => 'site/error',
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>require('params.php'),
);
you can customize how to show the error log for your development and production server
development.php // you can customize the packages imported for development and production
return CMap::mergeArray(
array(
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=mydb',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
),
array(
'class' => 'CWebLogRoute',
),
array(
'class' => 'CDbLogRoute',
'levels' => 'trace, info, warning, error',
'connectionID' => 'db',
'autoCreateLogTable' => true,
),
),
),
),
),
require('main.php')
);
production.php
return CMap::mergeArray(
array(
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=myserver.com;dbname=mydb',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'mypassword',
'charset' => 'utf8',
'tablePrefix' => '',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
),
array(
'class' => 'CDbLogRoute',
'levels' => 'trace, info, warning, error',
'connectionID' => 'db',
'autoCreateLogTable' => true,
),
),
),
),
),
require('main.php')
);
just run the development or production configuration rather than main config

My problem was I was actually loading "index.php" when I wanted "index-dev.php".
My .htaccess redirect wasn't working for "localhost/" but it was working for "localhost/page".
I've got it working now by typing "localhost/index-dev.php

If you're using Yii you can also use the CMap::mergeArray function which does what the longer version of the accepted answer does already.
The last part of my index file looks like this:
$configMain = require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'main.php');
$configServer = require_once( dirname( __FILE__ ).DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'main' . $env . '.php' );
require_once($yii);
$config = CMap::mergeArray( $configMain, $configServer );
// Set Path alias for all javascript scripts
Yii::setPathOfAlias('js', dirname($_SERVER['SCRIPT_NAME']).DIRECTORY_SEPARATOR."js/");
Yii::createWebApplication($config)->run();
The part left out is at the top where I determine if I'm local or on the server.

Related

Yii: Outputting variables for testing- echo and logging doesn't work

I'm working a Yii project passed down to me. As I'm very new to the thing, my first instinct was to do output a whole bunch of values to get a sense as to where things come from and where they go.
So to that end, I tried using echo in the Controller. As in:
public function actionCallCommentForm($id='')
{
$topic=Forum::model()->findByPk($id);
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
$this->renderPartial('_commentform', array(
'forum'=>$topic,
'model'=>new Comment,
'view'=>'view',
));
}
This, however, does not work. And I wouldn't know how to output, say, $topic, anyway, if it did.
So I tried logging. Based on the answer to this question:
public function actionCallCommentForm($id='')
{
$topic=Forum::model()->findByPk($id);
Yii::trace(CVarDumper::dumpAsString("TESTING!"));
Yii::trace(CVarDumper::dumpAsString($topic));
$this->renderPartial('_commentform', array(
'forum'=>$topic,
'model'=>new Comment,
//'view'=>array('view','id'=>$id),
'view'=>'view',
));
}
Upon checking the logs though (which does work for outputting errors) in runtime/application.log
The answer says The Application Log is shown below in every page. but I'm afraid that's not clear.
Any other ways to do this?
EDIT: More details:
main.php:
<?php
// load the helper functions - jim
require_once( dirname(__FILE__) . '/../components/Helpers.php');
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'Star Connects',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'application.modules.poll.models.*',
'application.modules.poll.components.*',
'ext.multimodelform.MultiModelForm',
'ext.mail.YiiMailMessage',
),
'aliases' => array(
'xupload' => 'ext.xupload'
),
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'manager1',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array($_SERVER['REMOTE_ADDR'],'127.0.0.1','10.0.1.100'),
),
'poll' => array(
// Force users to vote before seeing results
'forceVote' => TRUE,
// Restrict anonymous votes by IP address,
// otherwise it's tied only to user_id
'ipRestrict' => TRUE,
// Allow guests to cancel their votes
// if ipRestrict is enabled
'allowGuestCancel' => FALSE,
),
/* 'message' => array(
'userModel' => 'User',
'getNameMethod' => 'getFullName',
'getSuggestMethod' => 'getSuggest',
), */
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
'class'=>'WebUser',
'loginRequiredAjaxResponse' => 'YII_LOGIN_REQUIRED',
),
'session'=> array(
'timeout'=> 1440
),
'partyroles'=>array(
// enable cookie-based authentication
'class'=>'WebUser',
),
// uncomment the following to enable URLs in path-format
/*
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
/*
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
), */
// uncomment the following to use a MySQL database
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'index.php?r=site/login/<msg>'=>'site/login',
),
),
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=dbtest',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
//'tablePrefix' => 'tbl_',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
array(
'class' => 'CWebLogRoute',
'enabled' => YII_DEBUG,
'levels' => 'error, warning, trace, notice',
'categories' => 'application',
'showInFireBug' => true,
),
),
),
'mail' => array(
'class' => 'ext.mail.YiiMail',
'transportType' => 'smtp',
'transportOptions' => array(
'host' => '10.236.9.116',
'username' => '',
'password' => '',
#'port' => 0,
'encryption'=>'ssl'
),
'viewPath' => 'application.views.mail',
'logging' => true,
'dryRun' => false
)
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
index.php in project folder:
<?php
// change the following paths if necessary
$yii=dirname(__FILE__).'/../../yii-1.1.12/framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
Yii::createWebApplication($config)->run();
Instead of Yii::trace(), you can try to use Yii::log():
public function actionCallCommentForm($id='')
{
$topic=Forum::model()->findByPk($id);
Yii::log(CVarDumper::dumpAsString("TESTING!"));
Yii::log(CVarDumper::dumpAsString($topic));
$this->renderPartial('_commentform', array(
'forum'=>$topic,
'model'=>new Comment,
//'view'=>array('view','id'=>$id),
'view'=>'view',
));
}
My configuration for logging is:
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'info, error, warning', // info is necessary, if you want to use Yii::log() without second parameter
),
),
),
And it writes informations passed by Yii::log() function to runtime/application.log file.
EDIT:
in main.php in returning array you need to have this code:
'preload'=>array('log'),
Without this configuration option, logging utility doesn't work.
EDIT 2:
When using Yii::log() without second parameter, which determines level, default level is info. In your main.php config file there is no level info, so please add it to levels string in routes array.

The storage configuration for OAuth2 is missing when 'config_cache_enabled' is set to true

I'm using zf2 apigility in my web application. With production mode, if config_cache_enabled is true in config/application.config.php, I get this message error when requesting access_token:
The storage configuration for OAuth2 is missing
If I set it to false, I get my access token.
So my problem is to have config_cache_enabled set to true and a successful request for getting the access token in production mode, due to best performance when configuration is cached. How to do that ?
This is my zf-mvc-auth configuration :
'zf-mvc-auth' => array(
'authentication' => array(
'adapters' => array(
'CustomStorage' => array(
'adapter' => 'ZF\\MvcAuth\\Authentication\\OAuth2Adapter',
'storage' => array(
'storage' => 'Application\\Adapter\\OAuth\\CustomPdoAdapter',
'route' => '/oauth',
),
),
),
),
),
This is my oauth2.local.php :
'zf-oauth2' => array(
'db' => array(
'dsn' => 'mysql:dbname=mydatabase;host=localhost',
'username' => 'root',
'password' => '',
),
'allow_implicit' => true,
'access_lifetime' => 3600,
'enforce_state' => true,
'storage' => 'Application\Adapter\OAuth\CustomPdoAdapter',
'storage_settings' => array(
'user_table' => 'users',
),
'options' => array(
'always_issue_new_refresh_token' => true,
),
),
I think it is well configured.
Did you setup your zf-mvc-auth correctly. In the module.config.php you can read that you have to define a storage key. There is also written how you can do this:
To specify the storage instance, you may use one of two approaches:
Specify a "storage" subkey pointing to a named service or an array
of named services to use.
Specify an "adapter" subkey with the value "pdo" or "mongo", and
include additional subkeys for configuring a ZF\OAuth2\Adapter\PdoAdapter
or ZF\OAuth2\Adapter\MongoAdapter, accordingly. See the zf-oauth2
documentation for details.
If you are on production mode and "config_cache_enabled" it's true, you need to delete files on data/cache folder

Zend Framework 2 + Doctrine 2 Custom configuration with YML mapping not working

I am trying a different configuration to working with a new Project.
What I want to do is to create a database by writing sql on hand.
After it I want to do a convert-mapping from database to "YML" instead of php annotations.
So, to finish it, I want to convert those YML mapping information to Doctrine Entity, inside a ZF2 Module.
I am Using in composer:
"doctrine/doctrine-orm-module" : "0.7.0",
"doctrine/doctrine-module" : "0.7.*",
In global.php configuration
'doctrine' => array(
'connection' => array(
// default connection name
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => '****',
'dbname' => 'gear',
'charset' => 'utf8'
),
)
)
),
On the Target Module
'doctrine' => array(
'driver' => array(
/* This is where you can change the Mapping Driver */
'orm_default' => array(
'drivers' => array(
'Application\Entity' => 'application_entities_yaml'
),
),
'application_entities_yaml' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
'paths' => array(__DIR__ . '/../src/' .__NAMESPACE__. '/Yml')
),
),
),
I am looking to use a custom place to put the YML annotations, on a ZF2 Action I use a exec thats generate this command:
vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping --namespace="Gear\\Entity\\" --force --from-database yml module/Gear/src/Gear/Yml
Who saves correcty the YML mapping data into the folder module/Gear/src/Gear/Yml
It is exactly the path that I put into "application_entities_yaml" in the module config file.
But when i try to finally create the Entitys to get the work done, with this command:
vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities module/Gear/src/
or with
vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities --generate-annotations=1 module/Gear/src/
I got just:
'No Metadata Classes to process.'
I need to discovery how make Doctrine recognize where i put the metadata classes, to avoid this errors and go on with the project. I'll work with YML entities cuz is the best way to I teach non 'php' programmers write entities by the way. So is important to work with YML.
How to make Doctrine recognize those mapping and convert to entity without problems?
On the Target Module
Just change the Application\Entity to Module\Entity aka Gear\Entity and it works!
'doctrine' => array(
'driver' => array(
/* This is where you can change the Mapping Driver */
'orm_default' => array(
'drivers' => array(
'Gear\Entity' => 'application_entities_yaml'
),
),
'application_entities_yaml' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
'paths' => array(__DIR__ . '/../src/' .__NAMESPACE__. '/Yml')
),
),
),

Yii framework new column in database not showing in output of $model->getAttributes() method call?

Yii version 1.1.8
I have added a column to a table in a mysql database,
but the new column is not showing in output of $model->getAttributes() method call
I deleted all files in protected/runtime folder, but still no column
config: 'schemaCachingDuration' => 0, // in seconds. <1 means off
I can add data to the new column directly in the database.
Are there any other things that I can do to debug this?
index.php
<?php
// change the following paths if necessary
$yii=dirname(__FILE__).'/../../framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
// remove the following line when in production mode
//debug
defined('YII_DEBUG') or define('YII_DEBUG',true );
//show profiler
defined('YII_DEBUG_SHOW_PROFILER') or define('YII_DEBUG_SHOW_PROFILER',true);
//enable profiling
defined('YII_DEBUG_PROFILING') or define('YII_DEBUG_PROFILING',true);
//trace level
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
//execution time
defined('YII_DEBUG_DISPLAY_TIME') or define('YII_DEBUG_DISPLAY_TIME',false);
require_once($yii);
Yii::createWebApplication($config)->run();
main.php
<?php
return CMap::mergeArray(array(
'timeZone'=>'UTC',
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'catchAllRequest' => null, // null if online, array('site/offline') if offline,
'sourceLanguage' => 'en_ca',
'theme' => 'td',
'charset' => 'UTF-8',
'preload' => array('log'),
'import' => array(
'application.models.*',
'application.components.*',
'application.extensions.*'
),
'modules' => array(
),
// application components
'components' => array(
'format' => array(
),
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
'autoRenewCookie' => true,
),
'widgetFactory' => array(
'enableSkin' => true,
),
'urlManager' => array(
),
),
'db' => array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=mydb',
'emulatePrepare' => true,
'initSQLs'=>array("set time_zone='+00:00'"),
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => 'tbl_',
'enableParamLogging' => true, //show parameter values in log
// 'schemaCachingDuration' => 0, // in seconds. <1 means off
'enableProfiling' => YII_DEBUG_PROFILING, //show sql profile info in log
'nullConversion' => true,
//'initSQLs'=>array('set time_zone="+00:00"')
),
'errorHandler' => array(
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
'filter' => 'CLogFilter',
'enabled' => !YII_DEBUG
),
array(
'class' => 'CPhpMailerLogRoute',
'levels' => 'error',
'emails' => 'neilmcguigan+tderror#gmail.com',
'filter' => 'CLogFilter',
'enabled' => false,
),
array(
'class' => 'CWebLogRoute', // show log messages on web pages
'enabled' => YII_DEBUG,
'filter' => 'CLogFilter',
//'showInFireBug' => false
),
array(
'class' => 'CProfileLogRoute',
'enabled' => YII_DEBUG,
'showInFireBug' => false
)
),
),
'request' => array(
),
'securityManager'=>array(
)
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params' => array(
),
), require(dirname( __FILE__ ) . '/override.php'));
Having just went through this problem -- I found out the new field names need to be in the attributeLabels function in the model
public function attributeLabels()
{
return array(
'id' => 'ID',
'newfield' => 'New Field',
...
Be careful with using the "better still update overwrite your whole model" suggestion if you are like me and have a lot of custom code in your models. As Sankalp Singha suggests, Just copy the "diff" (green part) from using gii and add the part from attributeLabels to your code.
After you have added a new column in your table then just go to Gii and then click on model generator. In that put the name of your table again and then click preview. There would be an option of diff click on that and then copy the highlighted green code and copy paste it in your original modal or better still update overwrite your whole modal. Then check if you are able to get the values inside and are able to get the attributes. This should work.

Database could not connect to Zend Framework

I'm sorry I'm completely new to Zend Framework 2 with some tutorials I'm trying to connect my DB connection as follows,
Created a file in
xampp\htdocs\articlemanager\application\configs\autoload\global.php
Inserted the following Zend DB connection code to global.php
<?php
return array(
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),
'db' => array(
'driver' => 'PDO_MYSQL',
'dsn' => 'mysql:dbname=articlemanager;host=localhost',
'username' => 'root',
'password' => '',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
);
and In the Indexcontroller (\xampp\htdocs\articlemanager\application\controllers\IndexController.php) tested adding $this->db = $this->getServiceLocator()->get('db'); in the indexAction as follows
public function indexAction()
{
$this->db = $this->getServiceLocator()->get('db');
}
When I refresh page it display as
An error occurred
Application error
Can I know what I missed here?
Also I would like to know My Zend Library is in the \xampp\php\Zend and My global.php file in the xampp\htdocs\articlemanager\application\configs\autoload\global.php is it OK?
Why are you using an Alias on 'Db' ?
Try this, your driver name is different from mine.
In addition, please move your username and password to local.php.. so they do not persist in Git projects
global.php
<?php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=articlemanager;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
local.php example
<?php
return array(
'db' => array(
'username' => 'DB_USERNAME',
'password' => 'DB_PASSWORD',
),
);
database connection problems can be a number of different issues that are not necessarily obvious from looking at the creds / db config info.
have you taken a look at any logs? my application has several different logs setup - PHP error, access log, mysql error log, etc. - depending on your application, you may not have this many as discretely defined, but checking any logs you do have will give you a whole lot more information than just "An error has occurred" :)

Categories