Zend Framework 2: Disable module on production environment - php

OK, here's the problem:
I have a module in my Zend Framework 2 application that I wish to not include on production. Therefore, I made a file inside config/autoload called local.php with the following content:
'modules' => array(
'Application',
'My_Local_Module',
),
while config/application.config.php contains:
'modules' => array(
'Application',
),
When I try to access the module in the URL, a 404 is returned. However, when I set the modules inside the application.config.php file, the module is displayed properly. The environment variable is set to local.

Put the following lines in your index.php:
<?php
// ...
// Get the current environment (development, testing, staging, production, ...)
$env = strtolower(getenv('APPLICATION_ENV'));
// Assume production if environment not defined
if (empty($env)) {
$env = 'production';
}
// Get the default config file
$config = require 'config/application.config.php';
// Check if the environment config file exists and merge it with the default
$env_config_file = 'config/application.' . $env . '.config.php';
if (is_readable($env_config_file)) {
$config = array_merge_recursive($config, require $env_config_file);
}
// Run the application!
Zend\Mvc\Application::init($config)->run();
Then create different configuration files for each environment.
application.config.php:
<?php
return array(
'modules' => array(
'Application'
),
'module_listener_options' => array(
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php'
),
'module_paths' => array(
'./module',
'./vendor'
)
)
);
application.development.config.php:
<?php
return array(
'modules' => array(
'ZendDeveloperTools'
)
);
application.production.config.php:
<?php
return array(
'module_listener_options' => array(
'config_cache_enabled' => true,
'module_map_cache_enabled' => true,
'cache_dir' => 'data/cache/'
)
);

You have to enumerate all your modules inside application.config.php, so the config should look like that:
$modules = array (
'Application'
);
if (IS_LOCAL_DOMAIN)
{
$modules [] = "My_Local_Module";
}
return array(
'modules' => $modules,
'module_listener_options' => array(
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'./module',
'./vendor',
),
),
);

Related

Doctrine caching configuration

In the doctrine docs, it looks like I need the configuration object available for metadata caching:
<?php
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Configuration;
use Doctrine\Common\Proxy\ProxyFactory;
// ...
if ($applicationMode == "development") {
$cache = new \Doctrine\Common\Cache\ArrayCache;
} else {
$cache = new \Doctrine\Common\Cache\ApcCache;
}
$config = new Configuration;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver('/path/to/lib/MyProject/Entities');
$config->setMetadataDriverImpl($driverImpl);
However, this is currently inside a module in the zend directory in composer, so I cant change it. Id like to hand the option to do this in the array configuration:
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'params' => array(
'pdo' => new PDO("connection details")
),
'query_cache'=>new PhpFileCache(), //<- like this
'metadata_cache'=>new PhpFileCache(), //<- and this
),
),
),
I know this is possible because I have done it once before, however, I cant seem to find this method on the docs anymore. The current docs show the setup for YAML.
I can set up many connections in the Doctrine entity manager, but I supply one configuration since this sets up things that run once for the lifetime of that run, or if we have a cache installed such as APC, the lifetime of that release.
I achieve this by adding the info to $config['doctrine']['configuration'], not $config['doctrine']['orm_default/your_connection']['configuration']
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'params' => array(
'pdo' => new PDO("connection")
),
),
),
'configuration' => array(
'orm_default' => array(
'metadata_cache' => 'filesystem',
'query_cache' => 'filesystem',
'result_cache' => 'filesystem'
),
),
),

Zend Framework Module Setup

I'm trying to setup a module in the Zend Framework. Right now all I want is for it to go to my summary.phtml page, which will display Hello World.
I have setup the directory structure under my module directory as follows:
My files are as follows:
module.config.php
<?php
return array(
'controllers' => array(
'invokables' => array(
'BlindQC\Controller\BlindQC' => 'BlindQC\Controller\BlindQCController',
),
),
// The following section is new and should be added to your file
'router' => array(
'routes' => array(
'blinqc' => array(
'type' => 'Literal',
'options' => array(
'route' => '/summary',
'defaults' => array(
'__NAMESPACE__' => 'BlindQC\Controller',
'controller' => 'BlindQC',
'action' => 'summary',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'blindqc' => __DIR__ . '/../view',
),
),
);
BlindQCController.php
<?php
namespace BlindQC\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BlindQCController extends AbstractActionController{
public function summaryAction(){
}
};
summary.phtml
<h1>Hello World</h1>
autoload_classmap.php
<?php
return array();
Module.php
<?php
namespace BlindQC;
class Module {
public function getAutoloaderConfig() {
return array(
'Zend\Loader\ClassMapAutoloader' => array(__DIR__ . '/autoload_classmap.php',),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
}
I also modified my project's application.config.php to include my module:
// This should be an array of module namespaces used in the application.
'modules' => array(
'Application',
'UIExperiment',
'Developer',
'User',
'Project',
'Report',
'ProjectFamily',
'FMEProcessManager',
'BlindQC'
),
When I try to go to the summary route (/blindqc/summary) I get a 404. Any idea what I'm doing wrong?
All I had to do was change the route in module.config.php to /blindqc/summary and rename view/blindqc/blindqc to view/blind-qc/blind-qc in my directory structure.

ZendSkeleton 404 error - The requested URL could not be matched by routing

So I've been following the fairly straightforward zend 2 skeleton example "album". I followed every step to the teeth and yet I cannot escape the 404 Error - requested URL could not be matched by routing whenever I input http://hostname/album for indexing, or http://hostname/album/add for adding, etc.
Naturally I looked into the routing found in the module.config.php file:
<?php
return array(
'controllers' => array(
'invokables' => array(
'Album\Controller\Album' => 'Album\Controller\AlbumController',
),
),
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
);
Everything here looked fine, so I looked into the Module.php where the module.config.php is getting loaded from:
<?php
namespace Album;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
Again, everything looks fine here. Now I thought maybe the problem is that I didn't include the Album module in the application.config.php file (comments removed):
<?php
return array(
'modules' => array(
'Application',
'Album',
),
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
'config_glob_paths' => array(
'config/autoload/{{,*.}global,{,*.}local}.php',
),
);
However it is included. I also have the AlbumController.php and the view (.phtml) files exactly where they should be. I double checked the paths multiple times yet the routes still do not work. Any ideas? Any suggestion would be appreciated.
PS - I am using a Ubuntu 14.04 Virtual Box.
EDIT
Here's the directory structure for the application: (I'm just listing the relevant files/folders to make it more readable)
ZendSkel
public
index.php
config
application.config.php
module
Application
Album
Module.php
config
module.config.php
src
Album
Controller
AlbumController.php
Model
Form
view
album
album
index.phtml
add.phtml
edit.phtml
delete.phtml
Also, I am using virtual host with apache2.2.
For anyone, who is still looking for solution of this problem,
Clearing the data/cache folder, allowed routing to work as expected.
Like #Mayank Awasthi said:
Clearing the data/cache folder, allowed routing to work as
expected.
This applies to Zend AND Laminas.
If the issue is not cache related, check your config and routing files!
If you follwoing the tutorial in the official page step by step and it shows 404. make sure 1- stop the serve,
2- enter "composer development-enable".
3- enter "composer serve"
and then it should work. The tutorial does mention "composer development-enable" but it doesnt mention it in the right order, reason why a lot of people keep getting the 404

zend framework 2 - Cache config files

i'm trying to enable the cache for the config files in zend framework 2 :
the module.config.php ( part of services ) :
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
'doctrine.cache.mycache' => function ($sm) {
$cache = new \Doctrine\Common\Cache\MemcacheCache();
$memcache = new \Memcache();
$memcache->connect('localhost', 11211);
$cache->setMemcache($memcache);
return $cache;
},
),
),
the application.config.php ( part of enabling the cache for config ):
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
'config_cache_enabled' => true,
'config_cache_key' => md5('config'),
'module_map_cache_enabled' => true,
'module_map_cache_key' => md5('module_map'),
'cache_dir' => "./data/cache/modulecache",
),
And here the error i got :
Fatal error: Call to undefined method Closure::__set_state()
Thanks.
Config files can't be cached if they contain anonymous functions (in your case, the value for doctrine.cache.mycache). You will need to move just that part out of the config file and into your Module.php class' getServiceConfig() instead. That should fix the issue.

Yii config file override

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.

Categories