Invalid controller using custom routes - zend-framework

I've been following the instruction on how to create custom routes from the book Zend Framework - A Beginners Guide
I've changed my application.ini file to include this routing information:
resources.router.routes.static-content.route = /content/:page
resources.router.routes.static-content.defaults.module = default
resources.router.routes.static-content.defaults.controller = static-content
resources.router.routes.static-content.defaults.view = static-content
resources.router.routes.static-content.defaults.action = display
Given the above configuration, I have this controller:
<?php
class Default_StaticContentController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function displayAction()
{
// action body
$page = $this->getRequest()->getParam('page');
if (file_exists($this->view->getScriptPath(null) .
'/' . $this->getRequest()->getControllerName() . '/' .
$page . $this->viewSuffix
)) {
$this->render($page);
}
else {
throw new Zend_Controller_Action_Exception('HLC - Page not found', 404);
}
}
}
I have a view named about.phtml in the APPLICATION_PATH/modules/default/views/static-content folder.
What ahppens is I get an error saying:
An error occurred
Page not found
Exception information:
Message: Invalid controller class ("StaticContentController")
Stack trace:
#0 /Applications/MAMP/htdocs/zend/library/Zend/Controller/Dispatcher/Standard.php(262): Zend_Controller_Dispatcher_Standard->loadClass('StaticContentCo...')
#1 /Applications/MAMP/htdocs/zend/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#2 /Applications/MAMP/htdocs/zend/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#3 /Applications/MAMP/htdocs/zend/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#4 /Applications/MAMP/htdocs/HLC/public/index.php(26): Zend_Application->run()
#5 {main}
Request Parameters:
array (
'page' => 'about',
'module' => 'default',
'controller' => 'static-content',
'view' => 'static-content',
'action' => 'display',
)
Note that it is not rendering my customised Zend_Controller_Action_Exception but throwing the global error.
I'm using the URL: http://hlc.local:8888/content/about
The default index action works ok, just this routing that's not working.

if you are actually following the book closely, you have an extra line in your route declaration and your controller class should be StaticContentController.
here is the route definition from the book that does work.
resources.router.routes.static-content.route = /content/:page
resources.router.routes.static-content.defaults.module = default
resources.router.routes.static-content.defaults.controller = static-content
resources.router.routes.static-content.defaults.action = display
I still have this code laying around from last summer.
I found this book less then satisfactory and not really for beginners. It fails to address the Zend_Db component opting instead to introduce Doctrine 1.2. It's seems to be a trend that a number of these beginner/easy books feel that a full ORM is more useful then Zend_Db. If you are already familiar with Doctrine this approach works fine, otherwise it's a lot to ask of a beginner, to learn ZF and Doctrine at the same time.
Hope this helps.

I don't now what you use for autoloading. so that would helpful to determine.so far I understand your class named should be something like this ModulePath_ApplicationPath_ControllerName, so its Default_Application_StaticContentController.
and for better routing I preferred zend manual. you can try this tutorial for route. it would help for you.

Related

I keep getting this error on Slim 4 after installing new version 4.12

I keep getting this error Slim Application Error after installing the new Slim 4 framework.
I tried switching back to old version of slim but I keep getting the same thing.
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
/**
* Instantiate App
*
* In order for the factory to work you need to ensure you have installed
* a supported PSR-7 implementation of your choice e.g.: Slim PSR-7 and a supported
* ServerRequest creator (included with Slim PSR-7)
*/
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
/*
* Add Error Handling Middleware
*
* #param bool $displayErrorDetails -> Should be set to false in production
* #param bool $logErrors -> Parameter is passed to the default ErrorHandler
* #param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
// Run app
$app->run();
Output:
Slim Application Error
The application could not run because of the following error:
Details
Type: Slim\Exception\HttpNotFoundException
Code: 404
Message: Not found.
File: /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php
Line: 91
Trace:
#0 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(57): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Psr7\Request))
#1 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(Slim\Routing\RouteRunner))
#2 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(89): class#anonymous->handle(Object(Slim\Psr7\Request))
#3 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(class#anonymous))
#4 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(73): class#anonymous->handle(Object(Slim\Psr7\Request))
#5 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/App.php(206): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request))
#6 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/App.php(190): Slim\App->handle(Object(Slim\Psr7\Request))
#7 /opt/lampp/htdocs/MyocappAPI/public/index.php(41): Slim\App->run()
#8 {main}
I'm glad OP figured it out, but he didn't share his solution so here is what worked for me:
$app = AppFactory::create();
$app->setBasePath("/slimapp/public/index.php");
where the full path to my starter page is:
C:\xampp\htdocs\slimapp\public\index.php
To test my starter page, the URL I used was:
localhost/slimapp/public/index.php/hello/Beautiful
I think in Slim 3 you didn't need to manually set the base path, but you do in Slim 4. I don't know if it's a bug but this worked.
Slim 4 has some bugs in routing. So,Downgrade the slim version to 3.*
Reference:
https://discourse.slimframework.com/t/slim-4-httpnotfoundexception/3273/18

How to fix error "Cannot dispatch middleware Application\Middleware\IndexMiddleware"?

I've set up a Zend Application as normal, except in my case the difference is that I set it up over an existing legacy web application.
I still want to call my existing legacy application over the ZF3 app. It was suggested I can do so using Middleware. I went over https://docs.zendframework.com/zend-mvc/middleware/ and set up my routing as described there.
However, when I run the application, I am greeted by this:
Cannot dispatch middleware Application\Middleware\IndexMiddleware
#0 zend-mvc\src\MiddlewareListener.php(146):
Zend\Mvc\Exception\InvalidMiddlewareException::fromMiddlewareName('Application\\Mid...')
Here is where the exception happens:
https://github.com/zendframework/zend-mvc/blob/release-3.1.0/src/MiddlewareListener.php#L146
Just to note:
$middlewareToBePiped; //'Application\Middleware\IndexMiddleware'
is_string($middlewareToBePiped); // true
$serviceLocator->has($middlewareToBePiped);//false
$middlewareToBePiped instanceof MiddlewareInterface; //false
is_callable($middlewareToBePiped);//false
My class is:
namespace Application\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Zend\Http\Response;
class IndexMiddleware implements MiddlewareInterface
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
{}
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{}
}
I am thinking that my issue is that my IndexMiddleware class is not being found in ServiceLocator... (line 142 of linked API). How do I get it in there?
I put this into my application.config.php file:
'service_manager' => [
'invokables' => array(
'middleware' => IndexMiddleware::class
)
]
onto the next error it is.. (Last middleware executed did not return a response.)
but looks like it has executed)

Extbase can't use external PHP library

I am building a simple extension to display information on a Google Maps with Typo3.
I want to use the following PHP class (http://www.ycerdan.fr/developpement/google-maps-api-v3/) but I can't use it in my Controller.
I tried to use autoloading and require_once in my controller, but I just get PHP or Typo3 errors.
I guess it's a trivial problem, but I can't make it work despite lot of time searching.
Any help or hint are greatly appreciated ;)
General infos
Vendor name : CLICmap
Extension name : clicmap
Class location : Resources/Private/PHP
ext_autoloader.php :
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('clicmap');
return array(
'gmaps' => $extensionPath.'Resources/Private/PHP/GoogleMapAPIv3.class.php',
);
How I use it in my controller
public function listAction() {
$maps = $this->mapRepository->findAll();
$gmaps = $this->objectManager->get('gmaps');
$this->view->assign('maps', $maps);
}
The PHP error :
Uncaught TYPO3 Exception
#1289386765: Could not analyse class:gmaps maybe not loaded or no autoloader? (More information)
TYPO3\CMS\Extbase\Object\Container\Exception\UnknownObjectException thrown in file
/var/www/html/ftypo3/typo3/sysext/extbase/Classes/Object/Container/ClassInfoFactory.php in line 37.
Trying require_once :
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('clicmap');
require_once($extensionPath . 'Ressources/Private/PHP/GoogleMapAPIv3.class.php');
I get the following PHP error :
Warning: Uncaught exception 'TYPO3\CMS\Core\Error\Exception' with message 'PHP Warning: require_once(/var/www/html/ftypo3-fluid/typo3conf/ext/clicmap/Ressources/Private/PHP/GoogleMapAPIv3.class.php): failed to open stream: No such file or directory in /var/www/html/ftypo3/typo3conf/ext/clicmap/Classes/Controller/MapController.php line 52' in /var/www/html/ftypo3/typo3/sysext/core/Classes/Error/ErrorHandler.php:101 Stack trace: #0 /var/www/html/ftypo3/typo3conf/ext/clicmap/Classes/Controller/MapController.php(52): TYPO3\CMS\Core\Error\ErrorHandler->handleError(2, 'require_once(/v...', '/var/www/html/f...', 52, Array) #1 /var/www/html/ftypo3/typo3conf/ext/clicmap/Classes/Controller/MapController.php(52): CLICmap\Clicmap\Controller\MapController::listAction() #2 [internal function]: CLICmap\Clicmap\Controller\MapController->listAction() #3 /var/www/html/ftypo3/typo3/sysext/extbase/Classes/Mvc/Controller/ActionController.php(286): call_user_func_array(Array, Array) #4 /var/www/html/ftypo3/typo3/sysext/extbase/Classes/Mvc/ in /var/www/html/ftypo3/typo3/sysext/core/Classes/Error/ErrorHandler.php on line 101
Fatal error: CLICmap\Clicmap\Controller\MapController::listAction(): Failed opening required '/var/www/html/ftypo3-fluid/typo3conf/ext/clicmap/Ressources/Private/PHP/GoogleMapAPIv3.class.php' (include_path='/var/www/html/ftypo3-fluid/typo3/contrib/pear/:.:/usr/share/php:/usr/share/pear') in /var/www/html/ftypo3/typo3conf/ext/clicmap/Classes/Controller/MapController.php on line 52
EDIT : Solved
The code that solved my problem in the controller :
require_once(PATH_site . 'typo3conf/ext/clicmap/Resources/Private/PHP/GoogleMapAPIv3.class.php');//OK
$gmap = new \GoogleMapAPI();
I was messing with the filepath and most importantly i hadn't put a \ before my class instanciation.
The code that solved my problem in the controller :
require_once(PATH_site . 'typo3conf/ext/clicmap/Resources/Private/PHP/GoogleMapAPIv3.class.php');//OK
$gmap = new \GoogleMapAPI();
I was messing with the filepath and most importantly i hadn't put a \ before my class instanciation.

Zend_Navigation init in Bootstrap

Zend Framework v1.12
Tryed to init navigation in bootstrap and everything is fine, except appending it to view.
Here is a code snippet:
protected function _initNavigation() {
$this->bootstrap('view');
$view = $this->getResource('view');
include_once 'views/navigation.php';
$nav = new Zend_Navigation($navigation);
$view->navigation($nav);
}
Error occures because of last line. Stacktrace:
Uncaught exception 'Zend_Controller_Router_Exception' with message 'Route archive is not defined' in C:\OpenServer\domains\zend.vortexed\library\Zend\Controller\Router\Rewrite.php:318
Stack trace: #0 C:\OpenServer\domains\zend.vortexed\library\Zend\Navigation\Page\Mvc.php(176): Zend_Controller_Router_Rewrite->getRoute('archive') #1
C:\OpenServer\domains\zend.vortexed\library\Zend\View\Helper\Navigation\HelperAbstract.php(686): Zend_Navigation_Page_Mvc->isActive(false) #2
C:\OpenServer\domains\zend.vortexed\library\Zend\View\Helper\Navigation\Menu.php(740): Zend_View_Helper_Navigation_HelperAbstract->findActive(Object(Zend_Navigation), 0, NULL) #3
C:\OpenServer\domains\zend.vortexed\library\Zend\View\Helper\Navigation\Menu.php(940): Zend_View_Helper_Navigation_Menu->_renderMenu(Object(Zend_Navigation), 'navigation', '', ' ', 0, NULL, false, false, NULL, false, 'active', 'menu-parent', false) #4
C:\OpenServer\domains\zend.vortexed\library\Zend\View\Helper\Navigation\Menu.php(1096): Zend_View_Helper_Navigation_Menu->renderMenu(NULL)
...
Dumping $nav shows that it is good.
Also i tryed such variant:
protected function _initNavigation() {
$this->bootstrap('layout');
$layout= $this->getResource('layout');
$view= $layout->getView();
include_once 'views/navigation.php';
$nav = new Zend_Navigation($navigation);
$view->navigation($nav);
}
...same error
There are different reasons for that error,
Some of them are given in the following answer,
you can find it in here ROUTER EXCEPTION.
posting link as the answer, which helped The OP to get his answer, for the sake of marking the question as it has served it's purpose..
This is not a view or layout error.
The exception tell you that the route 'archive' is not define.
Start by creating the 'archive' route.

Zend error SQLSTATE[HY000] [1045]

I am having trouble with zend framework and connection with database, I'm trying to create a login, the table is created, and the code apparently is fine, but gives me this:
An error occurred
Application error
Exception information:
Message: SQLSTATE[HY000] [1045] Access denied for user 'onetag51_teste'#'localhost' (using password: YES)
Stack trace:
#0 C:\xampp\Zend\library\Zend\Db\Adapter\Pdo\Mysql.php(109): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 C:\xampp\Zend\library\Zend\Db\Adapter\Abstract.php(860): Zend_Db_Adapter_Pdo_Mysql->_connect()
#2 C:\xampp\Zend\library\Zend\Db\Adapter\Abstract.php(930): Zend_Db_Adapter_Abstract->quote('pass1', NULL)
#3 C:\xampp\Zend\library\Zend\Auth\Adapter\DbTable.php(449): Zend_Db_Adapter_Abstract->quoteInto('`password` = ?', 'pass1')
#4 C:\xampp\Zend\library\Zend\Auth\Adapter\DbTable.php(368): Zend_Auth_Adapter_DbTable->_authenticateCreateSelect()
#5 C:\xampp\Zend\library\Zend\Auth.php(117): Zend_Auth_Adapter_DbTable->authenticate()
#6 C:\xampp\htdocs\Eulen\application\controllers\AuthenticationController.php(27): Zend_Auth->authenticate(Object(Zend_Auth_Adapter_DbTable))
#7 C:\xampp\Zend\library\Zend\Controller\Action.php(516): AuthenticationController->logininAction()
#8 C:\xampp\Zend\library\Zend\Controller\Dispatcher\Standard.php(308): Zend_Controller_Action->dispatch('logininAction')
#9 C:\xampp\Zend\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#10 C:\xampp\Zend\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#11 C:\xampp\Zend\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#12 C:\xampp\htdocs\Eulen\public\index.php(26): Zend_Application->run()
#13 {main}
Request Parameters:
array (
'controller' => 'authentication',
'action' => 'loginin',
'module' => 'default',
)
I was searching for a solution, and some of the possible errors were, spelling errors(I didn't find any), can't connect to phpmyadmin using my pass and user(if I go to the phpmyadmim site, I can enter using the username and password).
I have try several solution but I cant figure it out.
Am I missing something.
file config.ini:
resources.db.params.charset = "utf8"
resources.db.adapter = "pdo_mysql"
resources.db.params.host = localhost
resources.db.params.username = "onetag51_teste"
resources.db.params.password = "*******"
resources.db.params.dbname = "onetag51_eulenhugo"
Its better to put here the authenticationcontroller, maybe the problem is there..
<?php
class AuthenticationController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function logininAction()
{
// action body
$authAdapter =$this->getAuthAdapter();
$username='hugo';
$password='pass1';
$authAdapter->setIdentity($username)
->setCredential($password);
$auth =Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if($result->isValid())
{
echo 'valid';
}
else
{
echo 'invalid';
}
}
public function logoutAction()
{
// action body
}
private function getAuthAdapter()
{
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password');
return $authAdapter;
}
}
ive been talking to a friend of mine, and he told me that i need to set the permission for acesse the phpmyadmim through zend...
How can i do that?
You don't need to use quotations around your adpater, username, password and dbname in your config file. I don't in mine, hope this helps.
I found a bit more reading that might be helpful access denied for user # 'localhost' to database '' because it mentions
You need grant privileges to the user if you want external acess to database(ie. web pages).
in the answer.
There is also this link about adding the users to the database in mysql.
Hope this helps
So the problem was related with the priveleges, thanks for ARJMP, ive tryed changed the priveleges but thee host didnd let me do it, so what i did was create a local database using xamp and try the login with the database that ive created in xamp, and it worked...