use custom helper in controller cakephp 3 - php

I am using cakephp v3 and want to ask how to use custom helper in controller
I have tried below code.
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Network\Request;
use Cake\ORM\TableRegistry;
use Cake\Auth\DefaultPasswordHasher;
use Cake\View\View;
use Cake\View\Helper\HtmlHelper;
use Cake\View\Helper\UrlHelper;
use Cake\View\Helper;
use App\View\Helper\SecurityHelper;
/**
* Static content controller
*
* This controller will render views from Template/Pages/
*
* #link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
*/
class PagesController extends AppController {
function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->viewBuilder()->helpers(['Security']);
}
public function receiveSaving() {
pr(($this->request->params['id'])); //die;
pr($this->Security->decrypt('7JCdO3vIqAU_EQUALS_')); die;
$this->viewBuilder()->layout('front');
$this->set('title', '');
$this->set('meta_title', '');
$this->set('meta_description', '');
$this->set('meta_keywords', '');
//$this->render('savings_bond_result');
}
and getting below error.
Error: Call to a member function decrypt() on boolean File
D:\xampp\htdocs\myproject\src\Controller\PagesController.php Line: 204
I tried with some other methods like
$Security = new SecurityHelper(new \Cake\View\View());
pr($Security->decrypt('7JCdO3vIqAU_EQUALS_')); die;
Error: Class 'App\Controller\SecurityHelper' not found File
D:\xampp\htdocs\myproject\src\Controller\PagesController.php Line: 204

$customdtfhelper = new \App\View\Helper\CustomDtfHelper(new \Cake\View\View());
$customdtfhelper->method_name();

Related

Attempted to call an undefined method named "redirect" error in Symfony 4

i have this error in my code and I have writing the "use" but i have this error:
Attempted to call an undefined method named "redirect" of class
"App\Controller\SetlocaleController".
My code:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SetlocaleController extends HomeController {
public function __construct(\Twig\Environment $twig)
{
$this->twig = $twig;
}
public function setLocaleAction(Request $request, $language = null)
{
if($language != null)
{
$session->set('_locale', $language);
}
$url = $request->headers->get('referer');
if(empty($url))
{
return new response($this->twig->render('page/home.html.twig'));
}
else{
return $this->redirect($url);
}
}
}
You have an answer for me please ?
Best practice solution
As proposed in the best practices for controllers documentation by Symfony, make sure you extend the Abstract controller on your controller.
// HomeController.php
// ...
class HomeController extends AbstractController {
// ...
No extra changes required to SetlocaleController. However if RedirectResponse is no longer used you can remove it's import
use Symfony\Component\HttpFoundation\RedirectResponse;
Solution using HttpFoundation\RedirectResponse
You need to use the already imported RedirectResponse object. Do not use the code: return $this->redirect($url); since, as the error states, there is no redirect(url) function defined for your class.
return new RedirectResponse($url);

Accessing method in another namespace

I'm trying to, from my controller, access a method in a model that is in another namespace and the only way I could do this was to make the method static. Is this the right way to do it, or is there any neater approach?
PagesController.php (controller):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\ConnectedHost;
class PagesController extends Controller
{
/*
* REMOVED CODE HERE FOR READABILITY
* Below is where I instantiate the "connectedHost"-object
*/
$hosts[$hostKey] = new ConnectedHost($hostAttributes['ipv4'], $hostAttributes['mac']);
}
/* REMOVED CODE HERE FOR READABILITY AS WELL */
ConnectedHost.php (helper-file):
namespace App\Helpers;
class ConnectedHost
{
public $ipv4, $mac;
public function __construct($ipv4, $mac)
{
$this->ipv4 = $ipv4;
$this->mac = $mac;
// This is where I call the getName-function staticly,
$this->name = \App\Host::getName();
}
}
Host.php (model):
namespace App;
use Illuminate\Database\Eloquent\Model;
class Host extends Model
{
// The method below is declared static
public static function getName()
{
$name = 'wenzzzel';
return $name;
}
}
If you are directly accessing the method from model like
$data = \App\ModelName::methodName();
Then your method should be static.
if your method is not static you can access like,
$model = new \App\ModelName();
$data = $model->methodName();

PHP Fatal error: Class 'App\Http\Controllers\View' not found In Laravel 5

Please Help To Solve This Problem
My Controller
<?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use View;
use DB;
class MyCon extends Controller {
/*
|--------------------------------------------------------------------------
| Welcome Controller
|--------------------------------------------------------------------------
|
| This controller renders the "marketing page" for the application and
| is configured to only allow guests. Like most of the other sample
| controllers, you are free to modify or remove it as you desire.
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application welcome screen to the user.
*
* #return Response
*/
public function register()
{
//return \View::make('pages.Register');
return view('pages.Register');
}
public function RegisterAction(Request $req)
{
$name = $req->input('name');
$email = $req->input('email');
$gender = $req->input('gender');
$password = $req->input('password');
$data = array("uname" => $name, "uemail" => $email, "ugender" => $gender, "upassword" => $password);
DB::table('user')->insert($data);
//return \View::make('pages.Register');
}
}
My Register Function work fine But When I am Submit Form ON RegisterAction function then show error like 'PHP Fatal error: Class 'App\Http\Controllers\View' not found'
My Router Code
Route::post('RegisterAction', 'MyCon#RegisterAction');
Please Help To Solve This Problem.
Thank In Advance
as you have changed the name like this
use Illuminate\Routing\Controller as BaseController;
change
class MyCon extends Controller {
to
class MyCon extends BaseController {
and you can use view helper function instead of importing View class yourself like this.
public function register()
{
return view('pages.Register');
}
Laravel Provides a nice helper to for View class.
return view('pages.Register');
Secondly you can also use
use View; //on top
View::make('pages.Register');
Hope this helps
Activate your APP DEBUGGER first so you can see your code issue by doing APP_DEBUG=true in your .env file.
including the View class in your controller won't give you an issue and restrict you to use the class or since you're using Laravel 5 you can use the function view() by simply calling view('SOMEVIEWHERE')
I suggest you redirect to a named route from route web file, try return redirect()->route('route-name'); and if you intend to use view try return view('view-name').
Using View::class means you are calling the view model which is not available except you have a view class created.

Extend Request class in Laravel 5

I'm new to Laravel (only experienced Laravel 5, so no legacy hang up here)
I'd like to know how to extend the core Request class. In addition to how to extend it, i'd like to know if it's a wise design decision to do so.
I've read through the documentation extensively (especially with regards to registering service providers and the manner in which it provides Facades access to entries within the dependency container) - but I can see (and find) no way to replace the \Illuminate\Http\Request instance with my own
Here is Official Document: Request Lifecycle
Content of app/Http/CustomRequest.php
<?php namespace App\Http;
use Illuminate\Http\Request as BaseRequest;
class CustomRequest extends BaseRequest {
// coding
}
add this line to public/index.php
$app->alias('request', 'App\Http\CustomRequest');
after
app = require_once __DIR__.'/../bootstrap/app.php';
change the code at public/index.php
Illuminate\Http\Request::capture()
to
App\Http\CustomRequest::capture()
I was working on the same issue today and I think it's worth mention that you may just change
Illuminate\Http\Request::capture()
to
App\Http\CustomRequest::capture()
without adding line
$app->alias('request', 'App\Http\CustomRequest');
because inside capture() method laravel actually binds provided class to service container with 'request' as a key
I guess you will have to extend also RequestForm. I use trait to avoid code duplication. Code below is relevant for Laravel 5.3.
app/Http/ExtendRequestTrait.php
<?php
namespace App\Http\ExtendRequestTrait;
trait ExtendRequestTrait {
methodFoo(){}
methodBar(){}
}
app/Http/Request.php
<?php
namespace App\Http;
use Illuminate\Http\Request as BaseRequest;
class Request extend BasicRequest {
use ExtendRequestTrait;
}
app/Http/FormRequest.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;
class FormRequest extend BasicFormRequest {
use ExtendRequestTrait;
}
For phpunit test working you will have to override call method to make it using right Request class here Request::create.
test/TestCase.php
<?php
use App\Http\Request;
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase{
// just copy Illuminate\Foundation\Testing\TestCase `call` method
// and set right Request class
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
$kernel = $this->app->make('Illuminate\Contracts\Http\Kernel');
$this->currentUri = $this->prepareUrlForRequest($uri);
$this->resetPageContext();
$request = Request::create(
$this->currentUri, $method, $parameters,
$cookies, $files,
array_replace($this->serverVariables, $server),
$content
);
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
return $this->response = $response;
}
}
and don't forget to switch Illuminate\Http\Request::capture() to App\Http\Request::capture() in public/index.php file and to add $app->alias('request', 'App\Http\Request'); after or inside $app = require_once __DIR__.'/../bootstrap/app.php';
Yerkes answer inspired me to write a custom class, for use with pagination, but only on specific requests
<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
class PaginatedRequest extends Request
{
public function page(): int
{
return max(1, (int) ($this['page'] ?? 1));
}
public function perPage(): int
{
$perPage = (int) ($this['per_page'] ?? 100);
return max(1, min($perPage, 500));
}
public function offset(): int
{
return ($this->page() - 1) * $this->perPage();
}
}
I then also had to register a new ServiceProvider in /config/app.php, which looks like
<?php
namespace App\Providers;
use App\Http\Requests\PaginatedRequest;
use Illuminate\Support\ServiceProvider;
class PaginatedRequestServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app->resolving(PaginatedRequest::class, function ($request, $app) {
PaginatedRequest::createFrom($app['request'], $request);
});
}
}
Now I can simply inject the PaginatedRequest in my controller methods only when I need it
<?php
namespace App\Http\Controllers;
use App\Http\Requests\PaginatedRequest;
class MyController
{
public function __invoke(PaginatedRequest $request)
{
$request->page();
// ...
}
}
I was able to add custom request object using FormRequest in Laravel 5.5 as follows.
First, just create FormRequest:
php artisan make:request MyRequest
Then just make it look like this:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
You can then use MyRequest as drop-in replacement in any function that takes Request as parameter:
public function get(MyRequest $request)
{
}
I do realize that FormRequests are actually meant to be used for a different purpose, but whatever works.
Documentation on FormRequest: https://laravel.com/docs/5.0/validation#form-request-validation
In Laravel 5.5.x, I was able to extend the Request class for specific requests using the following:
ExtendedRequest class
<?php declare(strict_types = 1);
namespace App\Http\Request;
use Illuminate\Http\Request;
class ExtendedRequest extends Request {
public function hello() {
echo 'hello world!';
}
}
ExtendedRequestServiceProvider
<?php declare(strict_types = 1);
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Http\Request\ExtendedRequest;
class ExtendedRequestServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(ExtendedRequest::class, function ($app) {
return ExtendedRequest::capture();
});
}
}
Then in your Controllers
<?php
namespace App\Controllers;
use App\Http\Request\ExtendedRequest;
class TestController extends Controller
{
public function get(ExtendedRequest $request) {
echo $request->hello();
}
}
Hope this helps someone.

Laravel Illuminate\Support\Facades\Input

I am new to Laravel and checking out some sample code.
In a controller I see this:
<?php
use Illuminate\Support\Facades\Input;
class RegistrationController extends \BaseController {
public function __construct()
{
$this->beforeFilter('guest');
}
Why do I have to use the "use Illuminate\Support\Facades\Input;" ?
Cant I just use eg Input::get(); like I do in my route file?
<?php
use Illuminate\Support\Facades\Input;
class RegistrationController extends \BaseController {
public function __construct()
{
$this->beforeFilter('guest');
}
this controller is in global namespace. so you don't need to use use Illuminate\Support\Facades\Input; you can directly call Input::get('foo');
<?php namespace Foo; //<---- check the namespace
use Input;
class RegistrationController extends \BaseController {
public function __construct()
{
$this->beforeFilter('guest');
}
here you can write either, use Input or \Input::get('foo') while calling.
You don't have to use importing namespaces (you don't need to add use Illuminate\Support\Facades\Input;) here.
You can accesss Input facade, using Input::get('something') as long as your controller is in global namespace. Otherwise you need to use \Input::get('something') or add use Input after <?php.

Categories