Custom views for errors in CakePHP 2.1 - php

I'm looking to create custom views for errors in CakePHP 2.1
I have been reading the following question here: CakePHP 2.0 - How to make custom error pages?
BUT there are somethings that do not work as expected!
1.) Exceptions and errors do not seem to be the same thing, as if I go to a bogus url I get the built in 404 page but if I manually do a notfound exception in the controller it will call the custom view... Why is this? I thought all errors in Cake went through the exceptions?
2.) I'm trying to render a view rather than ACTUALLY redirect the user...
so for example:
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
public function notFound($error) {
$this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
}
}
instead of that redirect I'm trying:
$this->controller->layout = null;
$this->controller->render('/Errors/error404');
but all I end up with is a blank page... Why is this? And this only happens when doing manual exceptions?
Can anyone answer these two questions please? Thanks

I've finally managed to get this figured out! Looking at the code from github, I've managed to get it working. Here's my AppExceptionRenderer.php:
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
public function missingController($error) {
$this->controller->render('/Errors/error404', 'layout');
$this->controller->response->send();
}
public function missingAction($error) {
$this->missingController($error);
}
}
If you want to call your controller callbacks you'll have to do something like this as well before beforeFilter():
$this->controller->beforeFilter();
That $this->controller->response->send(); line is the kicker. Hopefully this works for you!

This is simple,
public function notFound($error) {
$this->_outputMessage('error404');
}
That's all what you need to do

Simply:
throw new NotFoundException;
See the example code in the documentation about "Built in Exceptions".
App::uses('ExceptionRenderer', 'Error'); should not be required.
For an individual view edit View/Errors/error400.ctp.

Related

{"status":false,"error":"Unknown method"} error CodeIgniter RESTful API

<?php
include(APPPATH.'/libraries/REST_Controller.php');
class Quiz extends REST_Controller{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function user_get()
{
$this->load->model('Quizmodel');
$data = $this->Quizmodel->getAll();
$this->response($data, 200);
}
function restclient()
{
$this->load->library('rest', array(
'server' => 'http://localhost/CodeIg/index.php/quiz/'
));
$userr = $this->rest->get('user','','json');
echo $userr;
}
}
?>
I am able to get JSON output if I type http://localhost/CodeIg/index.php/quiz/user in my browser, however if I type http://localhost/CodeIg/index.php/quiz/restclient it gives this error: {"status":false,"error":"Unknown method"}
I tried changing get to post but still the same error.
I referred this page https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814 to do it.
You pinged me on GitHub, even though I haven't used or even thought about this code in at least 4 years.
https://github.com/chriskacerguis/codeigniter-restserver/blob/d19dc77f03521c7a725a4555407e1e4e7a85f6e1/application/libraries/REST_Controller.php#L680
This is where that error is being triggered. Throw a few breakpoints in there or var_dump()'s until you see what is causing the trouble.
You probably want to get off CodeIgniter though, and use something more actively maintained like SlimPHP or Lumen.
firstly I want as you have loaded rest api and created your controller quiz as an api to call , where you can only create your functions like user_get or restclient_get and access them the same manner you are doing.Just change you function name restclient to restclient_get then it will call instead it is even not running at this moment.

Auth component in Cakephp 3.0

I have a free installed instance of Cakephp 3.0 with several code examples, everything is working fine. Now I want to create a Auth component in ./src/Auth, concerning the documentation here
Thats my code:
<?php
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
class AlephAuthenticate extends BaseAuthenticate
{
public function authenticate(Request $request, Response $response)
{
// Do things for OpenID here.
// Return an array of user if they could authenticate the user,
// return false if not.
}
}
In AppContoller.php I initialize this component:
public function initialize() {
$this->loadComponent('Auth');
$this->Auth->config('authenticate', ['Aleph']);
}
Calling the application URL in the browser shows:
Fatal error: Declaration of App\Auth\AlephAuthenticate::authenticate() must be compatible with Cake\Auth\BaseAuthenticate::authenticate(Cake\Network\Request $request, Cake\Network\Response $response) in /var/www/art/src/Auth/AlephAuthenticate.php on line 7
Any idea whats wrong here?
Thanks!
Christoph
Please read the error message it is obvious. If you still have trouble understanding it just paste the error message into a search engine. This is the basic procedure for almost every error message if you don't know it and will probably always solve it. Guess it's in the php documentation as well.
Let me rephrase the error message for you: The method signatures don't match. To get rid off the error message make them match.

ZF2 routing and redirect function in controller

The following problem I am facing, error look likes this;
An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\Mvc\Exception\DomainException
File: .../vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Url.php:63
Message:
Url plugin requires that controller event compose a router; none found
I never faced this problem while I am trying to redirect from my controller. Lets say I implement the following function for redirection in my controller, which produces the error above;
public function __construct()
{
# Get user identity
$auth = new AuthenticationService();
if ($auth->hasIdentity()) {
$this->identity = $auth->getIdentity();
} else {
$this->redirect()->toRoute('admin/login');
}
}
The routing does exist as I can reach site.com/admin/login/ .. login is a child of admin so notation must be good. I am wondering what's going wrong and how to fix this issue or even, where to look for it would be a great starting point as well.
Thanks!
If you look at the error looks like you cant use the redirect plugin during the constructions of controller.
Url plugin requires that controller event compose a router; none found
might better to put that code in the onDispatch function like this.
public function onDispatch(MvcEvent $e)
{
# Get user identity
$auth = new AuthenticationService();
if ($auth->hasIdentity()) {
$this->identity = $auth->getIdentity();
} else {
return $this->redirect()->toRoute('admin/login');
}
return parent::onDispatch($e);
}
remember to return the redirect as otherwise the action will still be executed.

Laravel: Loading initial custom settings class

My aim is to fetch application concerned settings from a config file and load them to a DataSource and use it in the application. In the process of loading from the config file, I'd want to validate them and if they fail, Laravel should stop it's boot up. Sounds a bit a confusion, I guess. Hope the following example would help:
My config file appSettings.php is in app/config, just an example:
return array(
'color' => '',
'texture' => 'mixed',
'layers' => 3
);
My DataSource class DataSource.php is in source/DataSource.php, just an example:
public class DataSource {
public static function load() {
if (Config::get('appSettings.color').empty()) {
return false;
}
// Do other validations etc..
return true;
}
public function getColorForRoom($roomId) {
return something;
}
}
Now, what is the right place for me to call the method DataSource::load()?. DataSource will be used in the application for fetching certain data like calling getColorForRoom($roomId) function.
Maybe in intializers or somewhere I could do:
if (!DataSource::load()) {
// Stop booting up Laravel
}
But I'm not sure where exactly to put this and how to stop the application from booting up.
Possible Solutions
I'm not sure if this can be the right way, but it seems like a good approach:
In my bootstrap/start.php:
require $app['path.base'] . '/app/source/DataSource.php';
if (!DataSource::load()) {
Log::error("Failed to load datasource");
throw new ApplicationBootException();
}
Again, I'm not entirely sure about this. Is this a bad solution or are there any other better solutions?
The other possible solutions are loading DataSource from routes or filters as mentioned in the below answers.
Well - you could put it in the filters.php file
App::before(function($request)
{
if (!DataSource::load()) {
App::abort(500, 'Config is not correctly set');
}
});
Why don't you throw a custom Exception? Then you can catch this exception and redirect to a view that is like a 404 but custom to your application?
public class DataSource {
public static function load() {
if (Config::get('appSettings.color').empty()) {
throw new ApplicationBootException();
}
// Do other validations etc..
return true;
}
}
You could place this in the routes file.
App::error(function(ApplicationBootException $exception, $code){
//.. your code here to handle the exception
});
Please note I am just using ApplicationBootException as an example. You would have to create this class and have it extend Exception

Trying to debug a symfony app showing the list of all the functions called, debug_backtrace() doesn't fits me

im trying to debug a symfony app.
I've added a debug_backtrace() calling to this function below. It
outputs a list of functions called, but the save() function (that is
just before the debug_backtrace() calling) is not that list.. why? any other way to debug that shows more things, in this case the save() calling ?
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()));
if ($form->isValid())
{
$sf_guard_user = $form->save();
var_dump(debug_backtrace());
die("fsdgsgsdf");
$this->redirect('guardausuario/edit?id='.$sf_guard_user-
>getId());
}
}
Regards
Javi
I've just got my target using
xdebug_start_trace('/tmp/foo');
$usuario = $form->save();
xdebug_stop_trace();
http://www.xdebug.org/docs/all_functions
Javi
Symfony's web developer bar has some great information.
What exactly are you trying to see? Somethings it is good to echo $form because it will reveal all of the fields and any hidden fields in the form. Also, remember to include [_csrf_token] in your View if you are writing a custom View.
And... Symfony and xDebug are a good combination.
In php.net (http://php.net/manual/es/function.debug-print-backtrace.php) bishop exposes this solution:
$e = new Exception();
$e->getTraceAsString();
It gives a short but concise response for all the functions being called. It perfectly suited my needs, so I can log what happened without being lost.

Categories