Zend_Controller_Router_Exception: Route default is not defined - zend-framework

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.

Related

Zend Framework 1.12 Console commands

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

how to differentiate admin module from main application in bootstrap file in zend framework

Please give me proper solution for my query. I have tried to solve it but not getting any proper solution. Please give me proper solution.
If I remove following line from application.ini file then it is working well for front end application
resources.modules[] =
After remove it, I am unable to get my created module(Admin) in modules folder with proper layout. I have only one module. In module bootstrap file I have defined following functions (project/application/modules/admin/Bootstrap.php)
<?php
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected function _initAppAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'admin',
'basePath' => APPLICATION_PATH . '/modules/admin/'
));
return $autoloader;
}
protected function _initPlugins()
{
$bootstrap = $this->getApplication();
if ($bootstrap instanceof Zend_Application) {
$bootstrap = $this;
}
$bootstrap->bootstrap('FrontController');
$front = $bootstrap->getResource('FrontController');
$plugin = new Admin_Plugin_Layout();
// $plugin->setBootstrap($this);
$front->registerPlugin($plugin);
}
protected function _initAuthPlugin()
{
$checkAuth = Zend_Controller_Front::getInstance();
$checkAuth->registerPlugin(new Admin_Plugin_CheckAuth(Zend_Auth::getInstance()));
}
protected function _initDoctype()
{
global $adminModuleCssPath;
global $adminModuleJsPath;
$this->bootstrap( 'view' );
$view = $this->getResource( 'view' );
$view->headTitle('Jyotish - Ek Gyan');
$view->headScript()->appendFile($adminModuleJsPath.'jquery-1.7.2.js');
$view->headScript()->appendFile($adminModuleJsPath.'jquery-ui.js');
$view->headScript()->appendFile($adminModuleJsPath.'tinybox.js');
$view->headScript()->appendFile($adminModuleJsPath.'common.js');
$view->headLink()->appendStylesheet($adminModuleCssPath.'jquery-ui.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'style.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'theme.css');
$view->headLink()->appendStylesheet($adminModuleCssPath.'tinybox.css');
$view->doctype( 'XHTML1_STRICT' );
//$view->navigation = $this->buildMenu();
}
protected function _initLayoutPlugin()
{
$layout = Zend_Controller_Front::getInstance();
$layout->registerPlugin(new Admin_Plugin_AdminLayout());
}
protected function _initRouter()
{
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array('module' => 'admin')
);
$router->addRoute('default', $route);
$usersRoute = new Zend_Controller_Router_Route_Regex(
':module/:controller/:action/(?:/page/(\d+)/?)?',
array(
'module' => 'admin',
'controller' => 'users',
'action' => 'index',
'page' => 1,
),
array(
'page' => 1,
)
);
$router->addRoute('users-index', $usersRoute);
}
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . "/modules/admin/views/helpers");
Zend_Controller_Action_HelperBroker::addPrefix('Admin_View_Helper');
}
}
In modules folder I have created following plugin Layout
class Admin_Plugin_Layout extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
if ('admin' != $request->getModuleName()) {
// If not in this module, return early
return;
}
// Change layout
Zend_Layout::getMvcInstance()->setLayout('admin');
}
}
In frontend bootstrap file I have defined following functions(project/application/Bootstrap.php)
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initAppAutoload()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'default',
'basePath' => dirname(__FILE__),
));
return $autoloader;
}
protected function _initLayoutHelper()
{
$this->bootstrap('frontController');
$layout = Zend_Controller_Action_HelperBroker::addHelper(
new Application_View_Helper_LayoutLoader());
}
}
I have created following helper file in (project/application/view/helper/LayoutLoader.php)
<?php
class Application_View_Helper_LayoutLoader extends Zend_Controller_Action_Helper_Abstract
{
public function preDispatch()
{
$bootstrap = $this->getActionController()
->getInvokeArg('bootstrap');
$config = $bootstrap->getOptions();
$module = $this->getRequest()->getModuleName();
if (isset($config[$module]['resources']['layout']['layout'])) {
$layoutScript =
$config[$module]['resources']['layout']['layout'];
$this->getActionController()
->getHelper('layout')
->setLayout($layoutScript);
}
}
}
From last two days I am trying to create separate layout for both but I am unable to getting proper solution. When I run admin module in browser, it is working well but when I run frontend application folder it show exception error with layout of admin.
Please provide me proper solution....
Thanks
The standard way to do a layout switching is with a front-controller plugin. You don't need the LayoutLoader helper with preDispatch hook.
A simple layout-switcher plugin can be implemented as follows.
Place your various layout files in application/layouts/scripts/, named the same as your module: default.phtml, admin.phtml, etc.
In the file application/plugins/Layout.php:
class Application_Plugin_Layout extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
Zend_Layout::getMvcInstance()->setLayout($request->getModuleName());
}
}
Enable the plugin application/configs/application.ini using:
resources.frontController.plugins.layout = "Application_Plugin_Layout"
or by manually registering the plugin in Bootstrap.
Also, make sure your application.ini enables modules and identifies your layout location:
resources.modules[]=
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
You seem to be way over thinking this. I'm going to simplify this down to the basic and you can add back as you see fit.
The bootstrap system in ZF1 is a bad joke. Anything that is present in one of the bootstrap files will available to all modules at run and will be run with every request. So keep it simple and keep it light. I normally put all of the _init methods in the main bootstrap and leave the module bootstraps empty.
//simplify your bootstrap to minimum
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
//your app autoloader is the standard autoloader so is not needed here, it better just work.
/**
* initialize the session
*/
protected function _initsession()
{
Zend_Session::start();
}
/**
* initialize the registry and assign application.ini to config namespace
*/
protected function _initRegistry()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
}
protected function _initView()
{
//Initialize view
$view = new Zend_View();
//add custom view helper path
$view->addHelperPath('/../library/My/View/Helper');
//set doctype for default layout
$view->doctype(Zend_Registry::get('config')->resources->view->doctype);
//set default title
$view->headTitle('Jyotish - Ek Gyan');
//set css includes
$view->headlink()->setStylesheet('/bootstrap/css/bootstrap.min.css');
//add javascript files
$view->headScript()->setFile('/bootstrap/js/jquery.min.js');
$view->headScript()->appendFile('/bootstrap/js/bootstrap.min.js');
//add it to the view renderer
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer');
$viewRenderer->setView($view);
//Return it, so that it can be stored by the bootstrap
return $view;
}
/**
* Not sure if this is really required as it seems as though your routes are pretty standard.
*/
protected function _initRouter()
{
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array('module' => 'admin')
);
$router->addRoute('default', $route);
$usersRoute = new Zend_Controller_Router_Route_Regex(
':module/:controller/:action/(?:/page/(\d+)/?)?',
array(
'module' => 'admin',
'controller' => 'users',
'action' => 'index',
'page' => 1,
),
array(
'page' => 1,
)
);
$router->addRoute('users-index', $usersRoute);
}
protected function _initAuthPlugin()
{
$checkAuth = Zend_Controller_Front::getInstance();
$checkAuth->registerPlugin(new Admin_Plugin_CheckAuth(Zend_Auth::getInstance()));
}
}
The application.ini is a very important part of application configuration:
//truncated for example
[production]
;-------------------------------------------------------------------------------
;//PHP
;-------------------------------------------------------------------------------
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
;-------------------------------------------------------------------------------
;//Paths and Namespaces, paths for application resources and library
;-------------------------------------------------------------------------------
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
autoloaderNamespaces[] = "My_"
;-------------------------------------------------------------------------------
;//Front Controller, default settings for controllers and modules
;-------------------------------------------------------------------------------
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.frontController.moduleControllerDirectoryName = "controllers"
resources.frontController.params.prefixDefaultModule = ""
resources.modules = ""
resources.frontController.baseurl = http://example.com
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
;-------------------------------------------------------------------------------
;//plugins, default paths for resource plugins and action helpers, can also be
; //accomplished in the bootstrap
;-------------------------------------------------------------------------------
pluginPaths.My_Application_Resource = APPLICATION_PATH "/../library/My/Resource"
resources.frontController.actionhelperpaths.My_Controller_Action_Helper = APPLICATION_PATH "/../library/My/Controller/Action/Helper"
;-------------------------------------------------------------------------------
;//View Settings, view settings to be shared with the view object in the bootstrap
;// allows for easier editing.
;-------------------------------------------------------------------------------
resources.view[]=
resources.view.charset = "UTF-8"
resources.view.encoding = "UTF-8"
resources.view.doctype = "HTML5"
resources.view.language = "en"
resources.view.contentType = "text/html; charset=UTF-8"
;-------------------------------------------------------------------------------
;//Database Settings, default database adapter settings
;-------------------------------------------------------------------------------
resources.db.adapter = "pdo_Mysql"
resources.db.params.username = "user"
resources.db.params.password = "xxxx"
resources.db.params.dbname = "dbname"
resources.db.params.charset = "utf8"
resources.db.isDefaultTableAdapter = true
resources.db.params.profiler = true
;-------------------------------------------------------------------------------
;//Layouts, default path to layout files and default layout name
;-------------------------------------------------------------------------------
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.layout.layout = layout
Now the simplest way to accomplish layout switching is to switch the layout on a per controller basis, use the default layout except where you explicitly change it:
//some controller that needs the admin layout
//note: preDispatch() and routeShutdown() are essentially the same point in the loop
public function preDispatch() {
//switch to new layout
$this->_helper->layout->setLayout('admin');
//you can also manipulate the css and js similarly to the bootstrap
$this->view->headScript()->appendFile(
'/javascript/mediaelement/build/mediaelement-and-player.min.js');
$this->view->inlineScript()->setScript(
"$('audio').mediaelementplayer();");
}
I find that if I just need one or two different layouts this works nicely and is simple. Not really a DRY solution but can really help develop the parameters for a plugin if a DRY solution is desired.
I hope this provides some help, the big thing to remember is that the module bootstraps are basically just extentions of the main bootstrap and provide no seperation of functionality.
P.S. I would have provided a plugin demo but I really suck at plugins, Sorry.

Zend Framework autoloader in Doctrine 2 repositories

I use Zend Framework and Doctrine 2 in my project. Everything works fine except, that autoloader doesn't load Zend classes from Doctrine repositories.
Here is my bootstrap part for Zend autoloader:
/**
* Register namespace Default_
* #return Zend_Application_Module_Autoloader
*/
protected function _initAutoload() {
$autoloader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'Default_',
'basePath' => dirname(__FILE__),
));
return $autoloader;
}
Here is my bootstrap part for Doctrine initialization:
/**
* Initialize Doctrine
* #return Doctrine_Manager
*/
public function _initDoctrine() {
// include and register Doctrine's class loader
require_once('Doctrine/Common/ClassLoader.php');
$classLoader = new \Doctrine\Common\ClassLoader(
'Doctrine',
APPLICATION_PATH . '/../library/'
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'Repositories',
APPLICATION_PATH . '/../library/Model'
);
$classLoader->register();
// create the Doctrine configuration
$config = new \Doctrine\ORM\Configuration();
// setting the cache ( to ArrayCache. Take a look at
// the Doctrine manual for different options ! )
$cache = new \Doctrine\Common\Cache\ApcCache;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// choosing the driver for our database schema
// we'll use annotations
$driver = $config->newDefaultAnnotationDriver(
APPLICATION_PATH . '/../library/Model'
);
$config->setMetadataDriverImpl($driver);
// set the proxy dir and set some options
$config->setProxyDir(APPLICATION_PATH . '/../library/Model/Proxies');
$config->setAutoGenerateProxyClasses(true);
$config->setProxyNamespace('Model\Proxies');
// now create the entity manager and use the connection
// settings we defined in our application.ini
$connectionSettings = $this->getOption('doctrine');
$conn = array(
'driver' => $connectionSettings['conn']['driv'],
'user' => $connectionSettings['conn']['user'],
'password' => $connectionSettings['conn']['pass'],
'dbname' => $connectionSettings['conn']['dbname'],
'host' => $connectionSettings['conn']['host']
);
$entityManager = \Doctrine\ORM\EntityManager::create($conn, $config);
// push the entity manager into our registry for later use
$registry = Zend_Registry::getInstance();
$registry->entitymanager = $entityManager;
return $entityManager;
}
How could i fix this?
Your _initAutoload is completely unnecessary.
Just add
autoloadernamespaces[] = Default
autoloadernamespaces[] = Doctrine
to your application.ini
I agree that _initAutoload() shouldn't be necessary, but i suspect you'll need this in application.ini:
autoloaderNamespaces[] = "Doctrine"
autoloaderNamespaces[] = "Model"
If you just starting you project I will advice to use zf2 (beta5 last beta folowing: http://framework.zend.com/zf2/blog/entry/Zend-Framework-2-0-0beta5-Released)
This is tutorial which I was using for my project zf2 + doctrine 2 http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/

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 translate join multiple file languages

i am trying to add to my language file, the zend form errors language file, which can be found in
ZendFramework-1.11.2.zip\ZendFramework-1.11.2\resources\languages
in order to have localized form validators erorrs. This blog http://www.thomasweidner.com/flatpress/2010/03/25/working-with-multiple-translation-sources/comments/ explains what i try to do, but it fails :( it only translates from my .ini file, the .php is not included
Here is what i did:
this is my application.ini
resources.translate.adapter = "ini"
resources.translate.default.locale = "it_IT"
resources.translate.default.locale = "en_US"
resources.translate.default.file = APPLICATION_PATH "/lang/source-it.ini"
resources.translate.translation.en = APPLICATION_PATH "/lang/source-en.ini"
;resources.translate.data.directory = APPLICATION_PATH "/lang"
resources.translate.data = APPLICATION_PATH "/lang"
and then i have this
<?php
class Gestionale_Application_Resource_Translate extends Zend_Application_Resource_ResourceAbstract
{
public function init ()
{
$options = $this->getOptions();
$adapter = $options['adapter'];
$defaultTranslation = $options['default']['file'];
$defaultLocale = $options['default']['locale'];
$translate = new Zend_Translate($adapter, $defaultTranslation, $defaultLocale);
$translation_addme = new Zend_Translate(
'array',
APPLICATION_PATH."/resources/languages/it/Zend_Validate.php"
'it',
array('scan' => Zend_Translate::LOCALE_DIRECTORY)
);
$translate->addTranslation($translation_addme);
foreach ($options['translation'] as $locale => $translation) {
$translate->addTranslation($translation, $locale);
}
Zend_Registry::set('Zend_Translate', $translate);
return $translate;
}
}
and this is my dir
c:\www\www\gestionale\application>dir /w /aD
Il volume nell'unità C è OS
Numero di serie del volume: 6A5E-FD9B
Directory di c:\www\www\gestionale\application
[.] [..] [.svn] [configs] [controllers]
[forms] [lang] [layouts] [models] [resources]
[views]
0 File 0 byte
11 Directory 447.780.282.368 byte disponibili
Just by looking at your code I cannot tell you much. I suspect that your problems might be because you create your own resource plugin, which is unnessesry for this purpose, somethings are not being bootstrap properly, or there are some conflicts with your application.ini. Any way, I will post my translation setup and maybe it will give you some clues.
application.ini
Nothing here about translation or locale since I setup them in Bootstrap.php.
Bootstrap.php
protected function _initLocale() {
// define locale
$locale = new Zend_Locale('en');
// register it so that it can be used all over the website
Zend_Registry::set('Zend_Locale', $locale);
}
protected function _initTranslate() {
// Get Locale
$locale = Zend_Registry::get('Zend_Locale');
// Set up and load the translations (there are my custom translations for my app)
$translate = new Zend_Translate(
array(
'adapter' => 'array',
'content' => APPLICATION_PATH . '/languages/' . $locale . '.php',
'locale' => $locale)
);
// Set up ZF's translations for validation messages.
$translate_msg = new Zend_Translate(
array(
'adapter' => 'array',
'content' => APPLICATION_PATH .
'/resources/languages/' . $locale . '/Zend_Validate.php',
'locale' => $locale)
);
// Add translation of validation messages
$translate->addTranslation($translate_msg);
Zend_Form::setDefaultTranslator($translate);
// Save it for later
Zend_Registry::set('Zend_Translate', $translate);
}