Zend 2: How to configure errors with custom controller? - php

My question is regarding customizing how errors are handled in Zend 2.
Suppose I'd like to customize the layout such that I want to do this in an action in my controller:
$layout = $this->layout();
$myNav = new ViewModel(array('nav' => $this->getNav());
$myNav->setTemplate('layout/nav');
$layout->addChild($myNav, 'navigation');
Works great when I place this into my controller for regular (i.e. non-404) viewing. Now I've customized my layout so that I can do <?php echo $this->navigation; ?> and the layout/nav.phtml is fired up and everything works just hunky dory.
Now, suppose I want to do the exact same thing when errors are rendered. I need to be able to inject the above code somehow prior to the error handler returning it's own ViewModel(...) into the error/404.phtml template.
How do you do that?
I suspect that it's something like setting up the correct class for the service manager like this in module.config.php:
'service_manager' => array(
'services' => array(
'error_handler' => 'MyModule\Controller\MyCustomErrorController'
//and so on...
How do I do this?
UPDATE:
In my Module.php I've attached a method for MvcEvent::EVENT_DISPATCH_ERROR. Variant A works, Variant B does not. So you can't use partials here?? Am I missing something really basic??
Variant A
public function onDispatchError(MvcEvent $event)
{
$sm = $event->getApplication()->getServiceManager();
$vm = $event->getViewModel();
$vm->setVariable('nav', '<h1>test do i work?</h1>');
//Works
}
Variant B
public function onDispatchError(MvcEvent $event)
{
$sm = $event->getApplication()->getServiceManager();
$vm = $event->getViewModel();
$nav = new ViewModel(array('test'=>'hello there'));
$nav->setTemplate('layout/simpletest');//contents: <?php echo $this->test; ?>
$vm->addChild($nav, 'nav');
//In the template, <?php echo $this->nav; ?> has nothing...
}

Zf2 use module.config.php file to set error handling:
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
This should handle 4xx client errors and 5xx server errors.
For custom error page in specific module.
namespace ModuleName;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;
class Module implements
BootstrapListenerInterface,
AutoloaderProviderInterface,
ConfigProviderInterface
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('dispatch', array($this, 'loadConfiguration' ), 100);
}
public function loadConfiguration(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
$controller = $e->getRouteMatch()->getParam('controller');
if (0 !== strpos($controller, __NAMESPACE__, 0)) {
//if not this module
return;
}
//if this module
$exceptionstrategy = $sm->get('ViewManager')->getExceptionStrategy();
$exceptionstrategy->setExceptionTemplate('error/errorcustom');
}
public function getAutoloaderConfig(){ /* common code */ }
public function getConfig(){ /* common code */}
}
The solution is provided by "samsonasik" from http://samsonasik.wordpress.com/2012/09/19/zend-framework-2-create-custom-error-page/

You can attach to an even to handle what happend when a 404 is triggered:
Module.php
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
/**
* Log any Uncaught Errors
*/
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sm = $e->getApplication()->getServiceManager();
$sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
function($e) use ($sm) {
/**
* Decide what to do now we've got a problem...
* Log the issue etc..
* You could forward to some custom controller if you wanted..
*/
//$sm->get('Zend\Log\Logger')->crit('an error occurred... bla');
$controller = $e->getTarget();
//$routeMatch = $e->getRouteMatch();
$controller->layout('somelayout'); // possibly change the layout..
}
);
}

Related

Can not access my pages using acl and custom dispatcher

I'm currently using Phalcon 3.3 / PHP 7.2 (Ubuntu 18.04 LTS / Windows 10)
I created a custom SecurityPlugin file to verify user permission to access routes. I've defined my roles, resources and permission using Phalcon's ACL.
Here's my SecurityPlugin class
<?php
use Phalcon\Acl;
use Phalcon\Acl\Resource;
use Phalcon\Acl\Role;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;
/**
* Class SecurityPlugin
*
* This is the security plugin that makes sure users access the modules they are assigned to
*
*/
class SecurityPlugin extends Plugin
{
private function _getAcl()
{
if(!isset($this -> persistent -> acl))
{
$acl = new AclList();
$acl -> setDefaultAction(Acl::DENY);
//Add Roles
$roles = [
'base_acc' => new Role(
'BaseAcc',
'This role represents the standard users that are allowed on the platform'
),
'guest' => new Role(
'Guest',
'This is the default role assigned to users that are not logged in'
)
];
//Register Roles
foreach ($roles as $role) {
$acl -> addRole($role);
}
//Add Standard User Resources
$standardResources = [
'store' => ['index']
];
//Add Public Resources
$publicResources = [
'index' => ['index'],
'auth' => ['index', 'login', 'logout', 'register', 'confirmEmail', 'continueReg', 'finishReg', 'verifyPasswordToken', 'forgotPassword', 'updatePassword'],
'errors' => ['show404', 'show503', 'errorConfirm']
];
//Register Standard User Resources
foreach ($standardResources as $resource => $actions)
{
$acl -> addResource(new Resource($resource), $actions);
}
//Register Public Resources
foreach ($publicResources as $resource => $actions)
{
$acl -> addResource(new Resource($resource), $actions);
}
//Register Public Resources to all roles
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions){
foreach($actions as $action){
$acl -> allow($role -> getName(), $resource, $action);
}
}
}
//Register Standard Resources to standard User Role
foreach ($standardResources as $resource => $actions){
foreach($actions as $action){
$acl -> allow('BaseAcc', $resource, $action);
}
}
$this -> persistent -> acl = $acl;
}
return $this -> persistent -> acl;
}
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
$auth = $this->session->get('auth');
if (!$auth){
$role = 'Guests';
} else {
$role = 'BaseAcc';
}
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
$acl = $this->_getAcl();
if (!$acl->isResource($controller)) {
$dispatcher->forward([
'controller' => 'errors',
'action' => 'show404'
]);
return false;
}
$allowed = $acl->isAllowed($role, $controller, $action);
if (!$allowed) {
$dispatcher->forward([
'controller' => 'errors',
'action' => 'show401'
]);
//$this->session->destroy();
return false;
}
//Checks thr current user role
//$roles = [];
/*$auth = $this -> session -> get('auth');
if(!$auth)
{
$role = 'Guest';
}
else
{
$role = 'BaseAcc';
}
$acl = $this -> _getAcl();
$controller = $dispatcher -> getControllerName();
$action = $dispatcher -> getActionName();
$lastController = $dispatcher ->getLastController();
if(!$acl -> isResource($controller))
{
$dispatcher -> forward([
'controller' => 'errors',
'action' => 'show404'
]);
return false;
}
if(!$acl -> isAllowed($role, $controller, $action))
{
$dispatcher -> forward([
'controller' => 'errors',
'action' => 'show503'
]);
return false;
}*/
}
}
My part of my application bootstrap:
<?php
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');
error_reporting(E_ALL);
use Phalcon\Mvc\View as ViewEngine;
use Phalcon\Mvc\Model\MetaData\Files as MetaDataAdapter;
use Phalcon\Mvc\Application as AppEngine;
use Phalcon\Flash\Session as FlashService;
use Phalcon\Flash\Direct as FlashDirect;
use Phalcon\Session\Adapter\Files as SessionHandler;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
//use Phalcon\Logger\Adapter\File as LogService;
use Phalcon\Logger\Factory as LogFactory;
try{
//Try our Debugger
// = new Phalcon\Debug();
//$debug -> listen(true, true);
//Application Loader
$loader = new Phalcon\Loader();
//Register Working Directories
$loader -> registerDirs([
APP_PATH . '/controllers',
APP_PATH . '/config',
APP_PATH . '/models',
APP_PATH . '/cache',
APP_PATH . '/plugins',
BASE_PATH . '/vendor',
]);
//Register Namespaces
$loader -> registerNamespaces([
//'AgroTech\Models' => APP_PATH . '/models',
'AgroTech\Plugins' => APP_PATH . '/plugins'
]);
//Register Loader
$loader -> register();
// Use composer autoloader to load vendor classes
require_once BASE_PATH . '/vendor/autoload.php';
$di = new Phalcon\Di\FactoryDefault();
...
$di -> set('dispatcher', function() use ($di){
$eventsManager = $di->getShared('eventsManager');
//Bind our Custom Event Handlers
$eventsManager -> attach('dispatch:beforeExecuteRoute', new SecurityPlugin());
$eventsManager -> attach('dispatch:beforeException', new NotFoundPlugin());
//xdebug_print_function_stack();
$dispatcher = new Phalcon\Mvc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
...
$app = new AppEngine($di);
$response = $app -> handle();
$response -> send();
} catch(Phalcon\Exception $e){
echo "Exception: " . $e -> getMessage();
echo '<pre>' . $e -> getTraceAsString() . '</pre>';
}
However, binding the event 'dispatch:beforeExecuteRoute' with my SecurityPlugin gives me a 503 error. Disabling it makes all my pages acessible. And also, disabling my NotFoundPlugin (which handles invalid routes), I get a Dispatcher Cyclic routing error
Is there something I'm doing wrong?
Note: I based my SecurityPlugin implementation off https://github.com/phalcon/invo
What i can say? Just debug it with xdebug or even var_dumps and that's it? Check what is your $auth, controller, action etc in beforeExecuteRoute method and check what isAllowed is returning and how your acl object looks like after creating it and you will find your mistake easy.

Echo executed twice

I've added an ACL to my website but when I test the result of my role variable in the SecurityPlugin.php file I get the result twice.
Why does Phalcon show the var_dump of $role twice? I'm fairly new to this framework and my initial thought was it might me due to routing in Phalcon?
Phalcon version: 3.0.3
\app\plugins\SecurityPlugin.php
use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Resource;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
class SecurityPlugin extends Plugin
{
/**
* Returns an existing or new access control list
*
* #returns AclList
*/
public function getAcl()
{
if (!isset($this->persistent->acl)) {
$acl = new AclList();
$acl->setDefaultAction(Acl::DENY);
// Register roles
$roles = [
'admins' => new Role(
'admins',
'Website administrators'
),
'users' => new Role(
'users',
'Member privileges, granted after sign in.'
),
'guests' => new Role(
'guests',
'Anyone browsing the site who is not signed in is considered to be a "Guest".'
)
];
foreach ($roles as $role) {
$acl->addRole($role);
}
//Private area resources
$privateResources = array(
'account' => array('*')
);
$privateResourcesAdmin = array(
'admin' => array('*')
);
//Public area resources
$publicResources = array(
'index' => array('*'),
'register' => array('*'),
'errors' => array('show401', 'show404', 'show500'),
'register' => array('*'),
'login' => array('*'),
'logout' => array('*')
);
foreach ($privateResources as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
foreach ($privateResourcesAdmin as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
foreach ($publicResources as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
//Grant access to public areas to users, admins and guests
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions) {
foreach ($actions as $action){
$acl->allow($role->getName(), $resource, $action);
}
}
}
//Grant access to private area to role Users
foreach ($privateResources as $resource => $actions) {
foreach ($actions as $action){
$acl->allow('users', $resource, $action);
}
}
foreach ($privateResourcesAdmin as $resource => $actions) {
foreach ($actions as $action){
$acl->allow('admins', $resource, $action);
}
}
//The acl is stored in session, APC would be useful here too
$this->persistent->acl = $acl;
}
return $this->persistent->acl;
}
/**
* This action is executed before execute any action in the application
*
* #param Event $event
* #param Dispatcher $dispatcher
* #return bool
*/
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher){
$auth = $this->session->get('auth');
if (!$auth){
$role = 'guests';
} else {
if ($this->session->has("account_type")) {
$type = $this->session->get("account_type");
if($type == 99){
$role = 'admins';
} else {
$role = 'users';
}
}
}
var_dump($role);
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
$acl = $this->getAcl();
if (!$acl->isResource($controller)) {
$dispatcher->forward([
'controller' => 'errors',
'action' => 'show404'
]);
return false;
}
$allowed = $acl->isAllowed($role, $controller, $action);
if (!$allowed) {
$dispatcher->forward(array(
'controller' => 'errors',
'action' => 'show401'
));
$this->session->destroy();
return false;
}
}
}
\public\index.php
<?php
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Dispatcher; //Used for ACL list and authorization routing
use Phalcon\Events\Manager as EventsManager; //Used for ACL List
use Phalcon\Mvc\Router; //Used for routing logout page
error_reporting(E_ALL);
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');
try {
/**
* The FactoryDefault Dependency Injector automatically registers
* the services that provide a full stack framework.
*/
$di = new FactoryDefault();
/**
* Read services
*/
include APP_PATH . "/config/services.php";
/**
* Get config service for use in inline setup below
*/
$config = $di->getConfig();
/**
* Include Autoloader
*/
include APP_PATH . '/config/loader.php';
//This makes sure the routes are correctly handled for authorized/unauthorized in people
/**
* MVC dispatcher
*/
$di->set("dispatcher", function () use ($di) {
// Create an events manager
$eventsManager = $di->getShared('eventsManager');
/**
*Check if the user is allowed to access certain action using the SecurityPlugin
*Listen for events produced in the dispatcher using the Security plugin
*/
$eventsManager->attach(
"dispatch:beforeExecuteRoute",
new SecurityPlugin()
);
// Handle exceptions and not-found exceptions using NotFoundPlugin
$eventsManager->attach(
"dispatch:beforeException",
new NotFoundPlugin()
);
$dispatcher = new Dispatcher();
// Assign the events manager to the dispatcher
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
/**
* Handle and deploy the application
*/
$application = new \Phalcon\Mvc\Application($di);
echo $application->handle()->getContent();
} catch (\Exception $e) {
echo $e->getMessage() . '<br>';
echo '<pre>' . $e->getTraceAsString() . '</pre>';
}
Because you are doing forward - so this means there is other action executed again and beforeExecuteRoute fired again - that's why 2 times var_dump

Phalcon 3 and PHP 7 breaking the existing site

My problem started right after I upgraded PHP to Version 7 and Phalcon to Version 3.
Problem
I m getting blank page, no error messages (Error is turned on), no `500 Internal server' error in console. The site used to work flawlessly before.
I have following controller IndexController.php
<?php
namespace RealEstate\Property\Controllers;
use \Phalcon\Mvc\Controller;
use \Phalcon\Mvc\View;
use RealEstate\Common\Models as CommonModels;
class IndexController extends Controller
{
public function initialize(){
//Code here
}
public function indexAction(){
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
$this->view->setVar("total_properties", $this->utils->getTotalProperties());
$this->view->pick("index");
echo "HELLO WORLD";
}
}
The index action doesnot render anything, but yes HELLO WORLD is printed, so there seems there is no errors in code above that line.
My bootstrap index.php
<?php
namespace RealEstate;
use \Phalcon\Mvc\Application;
use \Phalcon\DI\FactoryDefault;
use \Phalcon\Loader;
use \Phalcon\Mvc\Router;
use \Phalcon\Mvc\View;
use \Phalcon\Mvc\Dispatcher;
use \Phalcon\Events\Manager as EventManager;
use \Phalcon\Assets\Manager as Assets;
use \Phalcon\Mvc\Url as UrlProvider;
use \Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use \Phalcon\Flash\Session as FlashSession;
use \Phalcon\Session\Adapter\Files as SessionAdapter;
use \Phalcon\Http\Response\Cookies;
//use \Phalcon\Session\Adapter\Files as Session;
class MyApplication extends Application
{
const DEFAULT_MODULE = "property";
private $prConfig;
/**
* Register the services here to make them general or register in the ModuleDefinition to make them module-specific
*/
protected function _registerServices()
{
try{
$config = include "../apps/config/config.php";
$di = new FactoryDefault();
$loader = new Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerDirs(
array(
__DIR__ . '/../apps/library/',
__DIR__ . '/../apps/plugins/'
)
);
$loader->registerNamespaces(array(
'RealEstate\Common\Plugins' => '../apps/plugins/',
'RealEstate\Common\Models' => '../apps/common/models/',
'RealEstate\Library\Pagination' => '../apps/library/',
'Facebook' => __DIR__.'/../apps/plugins/FacebookSDK/'
));
$loader->registerClasses(array(
"FacebookLib" => __DIR__.'/../apps/library/FacebookLib.php',
"Facebook" => __DIR__.'/../apps/plugins/FacebookSDK/autoload.php',
"MobileDetect" => __DIR__.'/../apps/library/MobileDetect.php'
));
$loader->register();
$di->set('config', $config, true);
//Register assets like CSS and JS
$di->set("assets",function(){
$assets = new Assets();
$cdnUrl = $this->cdnurl;
//Add CSS to collection. "true" means we're using base url for css path
$assets->collection('css')->addCss($cdnUrl.'assets/css/frontend/combined.css?v=44');
$assets->collection('footer')->addJs($cdnUrl.'assets/js/frontend/combined.js?v=44', false);
return $assets;
});
$this->prConfig = $config;
//register base url
$di->set('baseurl', function() use ($config){
$url = $config->application->baseUri;
return $url;
});
//register CDN url
$di->set('cdnurl', function() use ($config){
$url = $config->application->cdnUri;
return $url;
});
//Module Information
$di->set('appconfig', function() use ($config){
$appconfig = $config->application;
return $appconfig;
});
//Register URL helper
//set base url
$di->set('url', function() use ($config){
$url = new UrlProvider();
$url->setBaseUri($config->application->baseUri);
return $url;
});
//Register dependency for a database connection
$di->setShared('db', function() use ($config){
return new DbAdapter(array(
"host" => $config->database->host,
"username" => $config->database->username,
"password" => $config->database->password,
"dbname" => $config->database->dbname
));
});
//Register and start session
$di->setShared('session', function() {
$session = new SessionAdapter();
$session->start();
return $session;
});
//Register custom library Utilities, so that it is available through out the application
$di->setShared("utils",function(){
return new \Utilities();
});
//Registering a router
$di->set('router', function() use ($config){
$router = new Router(false);
$controller = "index";
/*Backend Routers Configuration Start*/
$modules = $config->modules;
$router->add('/', array(
'module' => 'property',
'namespace' => 'RealEstate\Property\Controllers\\',
'controller' => 'index',
'action' => 'index'
));
$router->add('/:int', array(
'module' => 'property',
'namespace' => 'RealEstate\Property\Controllers\\',
'controller' => 'index',
'action' => 'index',
'params' =>1
));
//other router settings
$router->notFound(array(
'module' => 'errors',
'namespace' => 'RealEstate\Errors\Controllers\\',
'controller' => 'index',
'action' => 'show404'
));
$router->removeExtraSlashes(true); //ignore trailing slash in urls
/*Backend Routers Configuration End*/
return $router;
});
$di->set('partials', function() {
$partials = new View();
$partials->setPartialsDir('../apps/common/views/');
return $partials;
});
$this->setDI($di);
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
public function main()
{
try{
if (!extension_loaded('phalcon')) {
die("Phalcon extension is not installed or enabled. Please check with host");
}
$this->_registerServices();
if($this->prConfig->application->environment=="development" || $_GET["showerrors"]==1){
ini_set("display_errors","On");
error_reporting(E_ALL ^ E_NOTICE);
}
$arraytemp = json_decode(json_encode($this->prConfig->modules), true); //convert Config object to a simple array
//$this->utils->printr($arraytemp,1);
$keys = array_keys($arraytemp);
$array = array();
if(count($keys)>0){
foreach($keys as $module){
$array[$module]["className"] = "RealEstate\\".ucwords($module)."\Module";
$array[$module]["path"] = "../apps/modules/".$module."/Module.php";
}
}else{
die("The entries for modules not found.");
}
$this->registerModules($array);
echo $this->handle()->getContent();
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
}
$application = new MyApplication();
$application->main();
Have followed This Link as well, but with not much help.
UPDATE
No errors on Server's error log
Thanks
I think I solved this issue. The issue was in Module.php, the issue was in method
public function registerServices($di)
{
try{
//Registering the view component
$di->set('view', function() {
$view = new View();
$view->setViewsDir('../apps/modules/'.$this->module_name.'/views/');
return $view;
});
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
Where, $module_name is a property defined in class.
In above code $this->module_name was undefined. so I changed above method to -
public function registerServices($di)
{
$module = $this->module_name;
try{
//Registering the view component
$di->set('view', function() use($module) {
$view = new View();
$view->setViewsDir('../apps/modules/'.$module.'/views/');
return $view;
});
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
I wondered why it was working in previous version of Phalcon

Repeat function in Laravel / PHP Class in one shared function

With the following code, how do I place the on_stats function in one area? So it can be shared and called in all functions on this page instead of copying and pasting the same code over and over again. Also how do I declare $logger just once instead of over and over again.
class API extends Controller
{
public function __construct() {
}
public function api_call1() {
$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$logger = new Logger('View Logs');
$logger->pushHandler(new StreamHandler(storage_path() . '/logs/api_log.log', Logger::INFO));
$res = $client->get($this->url . "/my/url/", [
'on_stats' => function (TransferStats $stats) use ($logger) {
$logger->info('Request' . $stats->getRequest()->getMethod() .
'Response' . $stats->getResponse()->getStatusCode() .
'Tx Time' . $stats->getTransferTime()
);
}
]);
$response = Response::make($res->getBody(), 200);
$response->header('Content-Type', 'application/json');
return $response;
}
public function api_call2() {
$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$logger = new Logger('View Logs');
$logger->pushHandler(new StreamHandler(storage_path() . '/logs/api_log.log', Logger::INFO));
$res = $client->get($this->url . "/my/url2/", [
'on_stats' => function (TransferStats $stats) use ($logger) {
$logger->info('Request' . $stats->getRequest()->getMethod() .
'Response' . $stats->getResponse()->getStatusCode() .
'Tx Time' . $stats->getTransferTime()
);
}
]);
$response = Response::make($res->getBody(), 200);
$response->header('Content-Type', 'application/json');
return $response;
}
}
From my viewpoint, it would be a great idea to:
Declare a class property as $logger
Move logger initialization to the constructor
Rewrite the "on_stats" method as a class method, say logEvent(TransferStats $stats) using $this->logger, this way you can avoid using "use" keyword
Pass the client event "on_stats" as a standard PHP callable array:
['on_stats' => [$this, 'logEvent']]

Symfony Request: setController, setAction, setModule

In zf2 I have the option to make fake requests with a Zend/Request object. Thus I can do an internal Request. I want to execute a part of my site with a few data. Thus, I must use a Controller, Module and a Action.
How would I do that?
Here's a snippet of code from zf2 from a previous question:
/application/controller/IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init(){}
public function indexAction()
{
//process some data from $_GET, $_POST, maybe (via framework, ofc).
}
}
/public/index2.php
<?php
//--cut--
$application->bootstrap();
$options = array(
'action' => 'index',
'controller' => 'index',
'module' => 'default'
);
if( isset($options['action'], $options['module'], $options['controller']) )
{
//*
$request = new Zend_Controller_Request_Http ();
$request->setModuleName($options['module'])->setActionName($options['action'])->setControllerName($options['controller']);
$frontController = Zend_Controller_Front::getInstance ()->returnResponse ( true );
//*/
$response = new Zend_Controller_Response_Http ();
$frontController->getDispatcher ()->dispatch ( $request, $response );
var_dump($response);
}
Thank you!

Categories