Recently, I used the Codeception inside PIMCore
in one of my project. And i found that it's very easy to implement and
helpful for the code-coverage report. Before that i also used the
PHPUnit tool for the Unit testing and code-coverage analysis.
Yes, Codeception is build on top of the PHPUnit and it makes some handy work to implement it.
I used the codeception inside the PIMCore, PIMCore is a tool for the CMS, CRM, E-Commerce development.
Although, PIMCore is built on Zend framework, So you can use the below steps to enable the codeception there.
Please follow the steps to enable and run the codeception inside PIMCore. Step 1: Install the codeception through the composer like below
# composer require "codeception/codeception"
Step 2: Check codeception is working or not, run the below command
# php vendor/codeception/codeception/codecept
Step 3: Install the codeception tests dir into your application
Step 5: Write up the test case assertions for all the functional logics.
class DummyTest extends \Codeception\Test\Unit
{
protected function _before()
{
}
protected function _after()
{
}
// tests
public function testDataBridge()
{
}
}
Step 6: Run the codeception with the below command:
# php vendor/codeception/codeception/codecept run
It will run the written functional unit cases and give you a report either no of pass or fail assertions.
Step 7. Install the xdebug module to get the code coverage report
# apt-get install
# /etc/init.d/apache2 restart
Enable the xdebug module
# phpenmod xdebug
# /etc/init.d/apache2 restart
Install the c3 module to get the code-coverage report
# composer require "codeception/c3"
Include c3.php in your index.php like
include "c3.php"
Step 8: Now you are ready to get the code-coverage report
Edit you codeception.yml file and add the below line to enable the coverage
coverage:enabled:true
For your further setting please have a look the below url
http://codeception.com/docs/11-Codecoverage
# php vendor/codeception/codeception/codecept run --coverage --coverage-html
It will give you a code-coverage report with html format.
Enable the Application cache in your ZF2 application:
Open your index.php file
Please below code: /** Is development environment or not */ define('DEVELOPMENT_ENV', (getenv('APP_ENV') === 'development') ? false : true);
Open your public/.htaccess file and place below line at end of the file: SetEnv "APP_ENV" "development"
Open your application.config.php file
Please below code in your file after module_path array:
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation. 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local,app}.php', ),
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests. 'config_cache_enabled' => DEVELOPMENT_ENV ? false : true,
// The key used to create the configuration cache file name. 'config_cache_key' => 'app-config',
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process. 'module_map_cache_enabled' => DEVELOPMENT_ENV ? false : true,
// The key used to create the class map cache file name. 'module_map_cache_key' => 'module-map',
// The path in which to cache merged configuration. 'cache_dir' => 'data/cache',
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded. 'check_dependencies' => DEVELOPMENT_ENV ? true : false
6. Provide full permission to data/cache dir That's it. Now run your application, after that you will see 2 files will be created inside data/cache dir that contains the
your application configuration at single place and
Your all class-map
It improves your application performance. Suggestion
: Please make enable cache configuration at your production/staging
servers only, better to disable cache at development server.
When you create REST-API then that API may consumed at Web or Mobile.
So, Its become important to capture the API information which was called from Web-User or Mobile-User.
API developer always want to know which method type, version, IP-Address and param used in consumed API.
So, I like to share the ZF2 Plugin that will help you to monitor the API calls.
Console based application has significant role for the users rather to use in web based apps.
In ZF2, there is a way to set console based application.
I like to address you guys on setting of console application inside Zend-Framework 2 in step-wise manner:
Step 1: Open your Module.php file for console based settings and place the below code:
1
2
3
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;use Zend\Console\Adapter\AdapterInterface as Console;
and implements the below interface on your Module class i.e.
1
class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInterface
Place the below function for the console banner and console usage inside Module.php file:
/** * To show the console banner * @see \Zend\ModuleManager\Feature\ConsoleBannerProviderInterface::getConsoleBanner() */publicfunctiongetConsoleBanner(Console$console){return"==------------------------------------------------------==\n"." Welcome to my ZF2 Console-enabled app \n"."==------------------------------------------------------==\n"."Version 0.0.1\n";}/** * This method is defined in ConsoleUsageProviderInterface */publicfunctiongetConsoleUsage(Console$console){returnarray('show logs'=>'Show application statistics','run cron'=>'Run automated jobs','(enable|disable) debug'=>'Enable or disable debug mode for the application.','show users'=>'Show active users','show all users'=>'show all users','show enable|disable users'=>'show enable|disable users');}
Step 2: Now if you run the application from console, then your have to run the below command where your application reside:
1
#phppublic/index.php
Then will get the below information:
If you get the same as above screen then this will give you some energy that you are on right track :) Step 3: Now you have to set the routing for the console i.e. passing route name after index.php file like:
1
#phppublic/index.phpshowlogs
To get this, we need to set that in module.config.php file of that Application module:
Step 4: Now your are on final destination to run the trigger of gun :)
Place the below code in your application controller file i.e. IndexController.php file:
1
2
3
4
5
6
7
8
9
public function showLogsAction() { $request = $this->getRequest(); // Make sure that we are running in a console and the user has not tricked our // application into running this action from a public web server. if (!$request instanceof ConsoleRequest) { throw new RuntimeException('You can only use this action from a console!'); } return "App Calling from the Console\n"; }
Now run the below command:
Simple... :)
If you want to learn more on this please follow the below URL:
<?phpnamespacemultiDB;useZend\Mvc\ModuleRouteListener;useZend\Mvc\MvcEvent;usemultiDB\Model\ClientDetailsTable;usemultiDB\Controller\multiDbActionController;usemultiDB\Adapter\MyAdapterFactory;classModule{publicfunctiononBootstrap(MvcEvent$e){$eventManager=$e->getApplication()->getEventManager();$moduleRouteListener=newModuleRouteListener();$moduleRouteListener->attach($eventManager);}publicfunctiongetConfig(){returnarray();}publicfunctiongetAutoloaderConfig(){returnarray('Zend\Loader\StandardAutoloader'=>array('namespaces'=>array(__NAMESPACE__=>__DIR__.'/src/'.__NAMESPACE__)));}/** * Get service configuration * * @access public * @return array */publicfunctiongetServiceConfig(){returnarray('factories'=>array('master'=>newMyAdapterFactory('master'),'client'=>newMyAdapterFactory('client'),'multiDB\Model\ClientDetailsTable'=>function($serviceManager){returnnewClientDetailsTable($serviceManager->get(multiDbActionController::getDb()));},));}}
Step 7: Now you have create all the files for the multiDB module inside your vendor directory. Now you just have to club it with your running modules.
Here, Some changes required in your global.php file where you mentioned the connection settings. Please see the demo file settings for the global.php file.
<?phpuseZend\Session\Container;/** * Global Configuration Override * * You can use this file for overriding configuration values from modules, etc. * You would place values in here that are agnostic to the environment and not * sensitive to security. * * @NOTE: In practice, this file will typically be INCLUDED in your source * control, so do not include passwords or other sensitive information in this * file. */$masterDB="master_db";$masterHost="localhost";$masterUser="root";$masterPassword="root";$session=newContainer('client');if(isset($_REQUEST['id']))$session->offsetSet('client_id',$_REQUEST['id']);$con=new\multiDB\Controller\multiDbActionController();$client=$con->getClientDb($masterDB,$masterHost,$masterUser,$masterPassword,$session->offsetGet('client_id'));$clientDB=$client['db_name'];$clientHost=$client['db_host'];$clientUser=$client['db_user'];$clientPass=$client['db_password'];$session->offsetSet('client_name',$client['client_name']);returnarray('master'=>array('driver'=>'Pdo','dsn'=>"mysql:dbname=$masterDB;host=$masterHost",'username'=>$masterUser,'password'=>$masterPassword),'client'=>array('driver'=>'Pdo','dsn'=>"mysql:dbname=$clientDB;host=$clientHost",'username'=>$clientUser,'password'=>$clientPass));
Step 8: Now you have to include multiDB module in application.config.php file
1
2
3
4
5
6
7
<?phpreturnarray(// This should be an array of module namespaces used in the application.'modules'=>array('Application','multiDB'//To handle multiple database on the fly),
Step 9: Now you have setup everything for the multi db connection. now you just call the services for the model.
For example: i use the default module "Application", where i change in the Module.php.
<?php/** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */namespaceApplication\Controller;useZend\Mvc\Controller\AbstractActionController;useZend\View\Model\ViewModel;useZend\Mvc\Application;useZend\Session\Container;useZend\EventManager\SharedEventManager;useApplication\Listener\ExampleEventsListener;useApplication\Entity\Product;useApplication\Form\CreateProduct;classIndexControllerextendsAbstractActionController{/** * Use to handle multiple database on the fly */publicfunctiondbswitchAction(){$dataset=$this->getServiceLocator()->get('Application\Model\TestModel');$emp=$dataset->getClientData();returnnewViewModel(array('data'=>$emp));}publicfunctionclientSetAction(){$view=newViewModel();$session=newContainer('client');$clientData="";if(isset($_REQUEST['id'])&&$_REQUEST['id']!=''){echo$clientData="Connected to the client ".$_REQUEST['id']." Client NAME: ".$session->offsetGet('client_name');$dataset=$this->getServiceLocator()->get('Application\Model\ClientModel');$data=$dataset->getClientDataSet();$session->offsetUnset('client_id');print_r($data);}$view->setTerminal(true);$session->offsetUnset('client_id');return$view;}}
Step 11: Create view file for the same action inside module... i.e. db-switch.phtml file inside application->index directory.
-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64)---- Host: localhost Database: master_db-- -------------------------------------------------------- Server version 5.5.38-0ubuntu0.14.04.1/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*!40101 SET NAMES utf8 */;/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*!40103 SET TIME_ZONE='+00:00' */;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;---- Table structure for table `client_schema`--DROP TABLE IF EXISTS `client_schema`;/*!40101 SET @saved_cs_client = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATETABLE`client_schema`(`id`int(11)NOTNULLAUTO_INCREMENT,`client_name`varchar(45)NOTNULL,`db_name`varchar(45)NOTNULL,`db_user`varchar(45)NOTNULL,`db_password`varchar(45)NOTNULL,`db_host`varchar(45)NOTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=latin1;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `client_schema`--LOCK TABLES `client_schema` WRITE;/*!40000 ALTER TABLE `client_schema` DISABLE KEYS */;INSERTINTO`client_schema`VALUES(1,'zend','zfskel','root','root','localhost'),(2,'test db 1','test_db1','root','root','localhost');/*!40000 ALTER TABLE `client_schema` ENABLE KEYS */;UNLOCKTABLES;/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2014-10-13 20:14:22
Another database i used it i.e. test_db1, dump of this database is:
-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64)---- Host: localhost Database: test_db1-- -------------------------------------------------------- Server version 5.5.38-0ubuntu0.14.04.1/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*!40101 SET NAMES utf8 */;/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*!40103 SET TIME_ZONE='+00:00' */;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;---- Table structure for table `employee`--DROP TABLE IF EXISTS `employee`;/*!40101 SET @saved_cs_client = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATETABLE`employee`(`id`int(11)NOTNULL,`name`varchar(45)DEFAULTNULL,`age`int(11)DEFAULTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBDEFAULTCHARSET=latin1;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `employee`--LOCK TABLES `employee` WRITE;/*!40000 ALTER TABLE `employee` DISABLE KEYS */;INSERTINTO`employee`VALUES(0,'kaushal',27),(1,'tarun',26),(2,'varun',34);/*!40000 ALTER TABLE `employee` ENABLE KEYS */;UNLOCKTABLES;/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2014-10-13 20:16:09