Zend Framework 1.12 Console commands - zend-framework

I'm using Zend Framework 1.12. I know it's too old and that's why not finding much support so putting this question here.
I have CronController and I'm calling it through curl request and its not a good approach. As the name specifies, I want to call its functions through the command-line. Please suggest how can I achieve this.
I have tried implementing https://docs.zendframework.com/zend-console/intro/ but it didn't help much.
Thanks in advance.

I assume that CronController is class extending Zend_Controller_Action like this:
class CronController extends Zend_Controller_Action
{
public function processAction()
{
// some very important logic
}
}
If so, don't use this in your CLI calls. Zend_Controller_Action should be used rather with HTTP requests, not CLI calls.
Move your business logic from this controller to separate classes, i.e.:
class My_Logic
{
public function process($options)
{
// some very important logic
}
}
Then, following DRY principle, create instance of this class in your controller:
class CronController extends Zend_Controller_Action
{
public function processAction()
{
$logic = new My_Logic();
$logic->process();
}
}
Now, create bin directory in root path of your project and put there your CLI script (i.e. cron.php):
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
$optsConfig = array(
'app_env=s' => 'Application environment name',
);
$opts = new Zend_Console_Getopt($optsConfig);
$opts->setOptions(
array(
'ignoreCase' => true,
'dashDash' => false,
)
);
$opts->parse();
defined('APPLICATION_ENV') || define('APPLICATION_ENV', $opts->app_env);
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->getBootstrap()->bootstrap();
class CronCli
{
public function doProcessing()
{
$logic = new My_Logic();
// here's your logic, the same as in controller
$logic->process();
}
}
$cmd = new CronCli($opts);
$cmd->doProcessing();
Now, you can call this script in your project's main directory:
php bin/cron.php --app_env production
production is your APP_ENV value name from application/configs/application.ini

Related

Zend_Controller_Router_Exception: Route default is not defined

I'm trying to test a controller. Zend Tool has generated the following code:
class Default_CarrinhoControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
}
public function testIndexAction()
{
$params = array('action' => 'index', 'controller' => 'Carrinho', 'module' => 'default');
$urlParams = $this->urlizeOptions($params);
$url = $this->url($urlParams);
$this->dispatch($url);
// assertions
$this->assertModule($urlParams['module']);
$this->assertController($urlParams['controller']);
$this->assertAction($urlParams['action']);
$this->assertQueryContentContains(
'div#view-content p',
'View script for controller <b>' . $params['controller'] . '</b> and script/action name <b>' . $params['action'] . '</b>'
);
}
}
PHPUnit Bootstrap
<?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
But it has failed and route is correct
Default_CarrinhoControllerTest::testIndexAction()
Zend_Controller_Router_Exception: Route default is not defined
C:\xampp\ZendFramework-1.11.11\library\Zend\Controller\Router\Rewrite.php:318
C:\xampp\ZendFramework-1.11.11\library\Zend\Controller\Router\Rewrite.php:469
C:\xampp\ZendFramework-1.11.11\library\Zend\Test\PHPUnit\ControllerTestCase.php:1180
C:\htdocs\farmaciaonline\FarmaciaOnlineWeb\tests\application\modules\default\controllers\CarrinhoControllerTest.php:16
C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php:939
C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php:801
C:\xampp\php\PEAR\PHPUnit\Framework\TestResult.php:649
C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php:748
C:\xampp\php\PEAR\PHPUnit\Framework\TestSuite.php:772
C:\xampp\php\PEAR\PHPUnit\Framework\TestSuite.php:745
C:\xampp\php\PEAR\PHPUnit\Framework\TestSuite.php:705
C:\xampp\php\PEAR\PHPUnit\TextUI\TestRunner.php:325
C:\xampp\php\PEAR\PHPUnit\TextUI\Command.php:187
C:\xampp\php\PEAR\PHPUnit\TextUI\Command.php:125
C:\xampp\php\phpunit:44
I have the default phpunit generated bootstrap by zend tool, I've setted up some custom routes but the default routes are still working on the application. What could be wrong?
Looks like there's an issue with the the Controller Test Case not setting the default route, if custom routes have been set (this is a different behavior than the framework).
The patch from the issue:
/**
* URL Helper
*
* #param array $urlOptions
* #param string $name
* #param bool $reset
* #param bool $encode
*/
public function url($urlOptions = array(), $name = null, $reset = false, $encode = true, $default = false)
{
$frontController = $this->getFrontController();
$router = $frontController->getRouter();
if (!$router instanceof Zend_Controller_Router_Rewrite) {
throw new Exception('This url helper utility function only works when the router is of type Zend_Controller_Router_Rewrite');
}
if ($default) {
$router->addDefaultRoutes();
}
return $router->assemble($urlOptions, $name, $reset, $encode);
}
You'll need to pass true as the last argument when using the url() function.
Instead of patching the Test Case, you can just add the default routes someplace in the bootstrap process:
$frontController->getRouter()->addDefaultRoutes();
This sounds like a typical problem you have not configured your app in the bootstrap properly and then invoking a request which leads to an undefined route. In your case the route is specified as Route default.
The route might be correct but just undefined.
For debugging purposes, output the $url you invoke so you see what's going on.

Zend Framework loads mappers from Application/Model/ instead of application/models

My zend app is created, everything seems to be in order but every time I try to do something like:
$accProducts = new Application_Models_AccProductsMapper();
Only get:
Warning: include_once(Application/Models/AccProductsMapper.php): failed to open stream: No such file or directory in /home/blah/blah/blah/Loader.php on line 148
however, the AccProductsMapper.php file do exist in such directory, directories within the zend app are all lowercase tough.
I've spend a lot of time looking for something to solve this issue with no good results at all.
Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
}
protected function _initAutoload()
{
$moduleLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH));
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace(array('App','My_'));
return $moduleLoader;
}
}
The standard Zend_Loader_Autoloader_Resource class added to each module looks for models with the class prefix <ModuleNamespace>_Model_ in <module-directory>/models.
For the default module, the namespace is defined in your config's appnamespace property (defaults to Application). The directory is typically application.
To summarize, create your default module model classes in application/models with class prefix Application_Model_, eg
<?php
// application/models/AccProductsMapper.php
class Application_Model_AccProductsMapper
{
// etc
As for your _initAutoload() method, I can't tell what you're doing with that module loader and would advise you don't need it at all. You can register PEAR style namespaces in your config file, eg
autoloadernamespaces.App = "App_"
autoloadernamespaces.My = "My_"

Zend Framework + PHPUnit + Netbeans

I am hardly struggling against problem I experience for last two days.
In fact I can not run test properly and receive:
PHP Fatal error: Call to undefined function Zend_Application() in
C:\xxxxxx\tests\application\controllers\IndexControllerTest.php on
line 10
IndexControllerTest is very simple and looks like this:
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
}
public function appBootstrap() {
$this->application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$this->application->bootstrap();
}
...
On the other hand bootstrap for tests contains only following code:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // /../application
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
Could you please help me with finding a problem? I would like to increase quality of mini project i indend to start but without testing it won't be possible.
Thank you in advance.
I added directories structure for my project. I keep zend libs in Source Files/library/Zend.
The error is coming from this:
$this->bootstrap = Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
You're missing a new before Zend_Application.
But, it's not clear to me what you have the appBootstrap function for unless you're going to use it:
public function setUp()
{
$this->appBootstrap();
parent::setUp();
}
What command are you using to run the tests?
If you don't load the bootstrap you'll get this error.
phpunit --bootstrap tests/bootstrap.php tests

Zend Framework - Where should we place our custom Validators?

We can read here how to write:
http://framework.zend.com/manual/en/zend.validate.writing_validators.html
class MyValid_Float extends Zend_Validate_Abstract
{
1)
Where should we place this?
application/default/validators ?
application/view/helpers/... ?
2)
Do we have to register this somewhere on our application ?
Update:
Here's an example of my bootstrap:
include_once 'config_root.php';
set_include_path ( $PATH );
require_once 'Initializer.php';
require_once "Zend/Loader.php";
require_once 'Zend/Loader/Autoloader.php';
// Set up autoload.
$loader = Zend_Loader_Autoloader::getInstance ();
$loader->setFallbackAutoloader ( true );
$loader->suppressNotFoundWarnings ( false );
// Prepare the front controller.
$frontController = Zend_Controller_Front::getInstance ();
$frontController->throwExceptions(true);
$frontController->registerPlugin ( new Initializer ( PROJECT_ENV ) );
// Dispatch the request using the front controller.
try {
$frontController->dispatch ();
} catch ( Exception $exp ) {
$contentType = "text/html";
header ( "Content-Type: $contentType; charset=UTF-8" );
echo "an unexpected error occurred.";
echo "<h2>Unexpected Exception: " . $exp->getMessage () . "</h2><br /><pre>";
echo $exp->getTraceAsString ();
}
SO, do I have to add here:
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
));
$resourceLoader->addResourceType('validate', 'validators/', 'My_Validate_');
And then I should create a file IN: (note that this configuration is using default module):
application/default/validators/ValidateSpam.php
And on validateSpam.php have something like:
class My_Validate_Spam extends Zend_Validate_Abstract {
Can you please confirm ?
Thanks
Place your application/validators
then in your application's Bootstrap class, add the following function:
protected function _initAutoload () {
// configure new autoloader
$autoloader = new Zend_Application_Module_Autoloader (array ('namespace' => '', 'basePath' => APPLICATION_PATH));
// autoload validators definition
$autoloader->addResourceType ('Validator', 'validators', 'Validator_');
}
More detail(s) about Zend Bootstrap Autoloading.
Another way is described in this blog, where the constructor of the controller for the form that is using this custom validator has an extra line:
class JD_Form_Controller extends Zend_Form
{
public function __construct($options = null)
{
// path setting for custom classes MUST ALWAYS be first!
$this->addElementPrefixPath('JD_Form_Validator','JD/Form/Validator','validate');
...
}
...
}
I do it by adding the following line to application.ini :-
autoloadernamespaces[] = "App_"
Then I put my custom validators in (for example) /library/App/Validate/MyCustomValidator.php.
I can then write my validator using something like:-
class App_Validate_MyCustomValidator() extends Zend_Validate_Abstract
It works pretty well for me and is simple and easy to implement.

Zend Framework Testing controller Zend_Controller_Exception: No default module defined for this application

I try to write test for controller. I use OS Windows, zend framework and my libraries are in C:/library which is added to the include_path of php.ini.
When I run test testLoginAction I get an error No default module define for the application. But I don't use modules at all. Do you know how to solve this problem?
IndexControllerTest.php
class Controller_IndexControllerTest extends ControllerTestCase
{
public function testIsEverythingOK()
{
$this->assertTrue(true);
}
public function testLoginAction()
{
$this->dispatch('/login/index');
$this->assertModule('default');
$this->assertController('login');
$this->assertAction('index');
}
}
ControllerTestCase.php
require_once 'Zend/Application.php';
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
protected $_application;
public function setUp()
{
$this->bootstap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
// require dirname(__FILE__) . '/bootstrap.php';
$this->front->setControllerDirectory('../application/controllers');
$this->_application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini');
$this->_application->bootstrap();
}
}
My phpunit.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit bootstrap="./application/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="true"
syntaxCheck="true">
<!-- запускаем все тесты из корневой директории -->
<testsuite name="Main Test Suite">
<directory>./</directory>
</testsuite>
<filter> <!-- смотрим лишь на следующие директории -->
<whitelist>
<directory suffix=".php">../application</directory>
<!-- <directory suffix=".php">../library</directory>-->
<exclude>
<directory suffix=".phtml">../application</directory>
<directory>../application/forms</directory>
<directory>../application/models</directory>
<directory>../library</directory>
<file>../application/Bootstrap.php</file>
</exclude>
</whitelist>
</filter>
<logging>
<!-- логирование и создание отчета -->
<log type="coverage-html" target="./report" charset="UTF-8" yui="true" highlight="true" lowUpperBound="35" highLowerBound="70"/>
</logging>
</phpunit>
My bootstrap.php in tests/application:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
require_once 'ControllerTestCase.php';
My Base class for tests:
require_once 'Zend/Application.php';
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
protected $_application;
public function setUp()
{
$this->bootstap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
// require dirname(__FILE__) . '/bootstrap.php';
$this->front->setControllerDirectory('../application/controllers');
$this->_application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini');
$this->_application->bootstrap();
}
}
Best regards, Oleg.
Make sure your application.ini does not contain configuration like resources.frontController.moduledirectory = APPLICATION_PATH "/modules" or resources.frontController.params.prefixDefaultModule = 1 or resources.modules[] =
You need to modify your setUp() method from the ControllerTestCase class, after parent::setUp() line:
$this->getFrontController()->setControllerDirectory(APPLICATION_PATH . '/controllers');
and remove the following line from your appBoostrap method:
$this->front->setControllerDirectory('../application/controllers');
$this->front-> won't work because the front controller property is $this->frontController-> or $this->getFrontController()->.
Even so, your tests probably won't work anyways because of the way you're bootstrapping. Are you configuring your front controller from an ini configuration file? If yes, then you don't need to configure the frontController in your tests, you need to configure your bootstrap by way of Zend_Application.
$this->bootstrap = new Zend_Application(
'testing',
APPLICATION_PATH . '/configs/application.ini'
);
You won't need to call bootstrap() on your Zend_Application instance because Zend_Test_PHPUnit_ControllerTestCase will do that when you dispatch a request.
So your base class might loook like this:
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
// Assign and instantiate in one step:
$this->bootstrap = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
parent::setUp();
}
}
And your controller test, extending your base class, will look like this:
class Controller_IndexControllerTest extends ControllerTestCase
{
public function testIsEverythingOK()
{
$this->assertTrue(true);
}
public function testLoginAction()
{
$this->dispatch('/login/index');
$this->assertModule('default');
$this->assertController('login');
$this->assertAction('index');
}
}
Done.
Resources
Bootstraping your TestCase