Creating and Accessing the Helper in the Controller - php

I've created a helper file in App folder named as Helper.php.
app/Helper.php
<?php
namespace App;
use Illuminate\Support\Facades\DB;
class Helper {
public function get_username($user_id)
{
$user = DB::table('users')->where('userid', $user_id)->first();
return (isset($user->username) ? $user->username : '');
}
}
app/Providers/HelperServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
public function boot()
{
//
}
public function register()
{
require_once app_path() . 'Helper.php';
}
}
config/app.php
Inside the provider's array...
App\Providers\HelperServiceProvider::class,
Inside aliases array...
'Helper' => App\Helper::class,
Everything was working fine but now I have the following error.
ErrorException thrown with message "Non-static method Helper::get_username($user->id) should not be called statically
But when I add static keyword to function its works fine. What's the difference between static and non-static methods?

Aliases give you the possibility to access a facade in a blade template without adding it in the template (vie use statement). When calling a method via a facade, you call this method statically and the facade will call the object of the class containing this method.
In Laravel, it is usually more convenient to create a file containing helpers like Laravel does and to autoload that file via composer.
Please check here for more details

Related

Laravel ReflectionException

I have a class called CustomerController with a delete function:
class CustomerController extends Controller
{
public function getAllCustomer()
{
return \App\model\Customer::get();
}
public function destroy (Customer $id)
{
$id->delete();
}
This is the route:
Route::delete('customer/{id}' , 'CustomerController#destroy');
I get this error:
Class App\Http\Controllers\Customer does not exist
I already tried Composer update and Composer dump-autoload with no success.
A screenshot:
Thank you very much!
When you do not include classes using use statements, php will try to find the class in the current namespace.
So, the function function destroy (Customer $id) will look for the class Customer in the App\Http\Controllers namespace. To avoid this, add a use statement for the App\model\Customer class above on top of your controller class. For example:
<?php
namespace App\Http\Controllers;
use App\model\Customer;
class CustomerController extends Controller
{
public function getAllCustomer()
{
return Customer::get();
}
public function destroy (Customer $id)
{
$id->delete();
}
}
Now you can also use a shorter name in the getAllCustomer() function.
Change this :
return \App\model\Customer::get();
to this:
add namespace at the top:
use App\Customer;
return Customer::get();
as you are using route model binding on delete action by injecting Customer class to the method therfore its failing so make sure you add model namespace at the top of the file(CustomerController).
The error is happening beacuse CustomerController is trying to look for Customer model in controllers namespace which means that your model namespace is wrong.

share method between controllers Laravel 5.2

In several controllers i have to use the same method to show results as table with column sorting functionality:
public function showSearchResults(Request $req){
$query=Service::where('title', $req->search);
// Columns sorting
if ($req->has('order')){
$order= $req->order=='asc' ? 'asc' : 'desc';
$order_inverse=$req->order=='asc' ? 'desc' : 'asc';
} else {
$order='desc';
$order_inverse='asc';
}
...
$url=$req->url().'?'.http_build_query($req->except('sortby','order','page'));
$results=$query->with('type')->paginate(15)->appends($req->all());
return View::make('services.search_results')
->with('results', $results)
->with('url',$url)
->with('sortby', $sortby)
->with('order', $order)
->with('order_inverse', $order_inverse);
}
What is the best approach to avoid DRY in such case?
Sharing methods among Controllers with Traits
Step 1: Create a Trait
<?php // Code in app/Traits/MyTrait.php
namespace App\Traits;
trait MyTrait
{
protected function showSearchResults(Request $request)
{
// Stuff
}
}
Step 2: use the Trait in your Controller:
<?php // Code in app/Http/Controllers/MyController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Traits\MyTrait; // <-- you'll need this line...
class MyController extends Controller
{
use MyTrait; // <-- ...and also this line.
public function getIndex(Request $request)
{
// Now you can call your function with $this context
$this->showSearchResults($request);
}
}
Now you can use your Trait in any other controller in the same manner.
It is important to note that you don't need to include or require your Trait file anywhere, PSR-4 Autoloading takes care of file inclusion.
You can also use Custom Helper classes as others have mentioned but I would recommend against it if you only intend to share code among controllers. You can see how to create custom helper classes here.
You can use traits (as ventaquil suggested) or you can create custom helpers file and add helpers there.
After that, you'll be able to use this helper from any class (controllers, models, custom classes, commands etc) like any other Laravel helper.
Use traits? More available here: http://php.net/manual/en/language.oop5.traits.php
You can create a helper file in your app directory. for eg. MethodHelper.php
In this file you can mention the method that you require using anywhere.
For instance,
<?php namespace App;
class MethodHelper
{
public static function reusableMethod()
{
//logic
}
}
You can use this method anywhere, by using the namespace and calling the method.
In the above eg.
The namespace would be:
The method call function would look like:
MethodHelper::reusableMethod();
You can send parameters too based on your functional requirements.
In your eg. you could have
public function showSearchResults(Request $req){
//
}
instead of reusableMethod().
Your call would be:
MethodHelper::showSearchResults($req);

Calling Models function in Controller in Pimcore

Example of controller file which have a function
use Api\Controller\Action;
class Api_WebserviceController extends Zend_Rest_Controller {
function xyz(){
echo "xyz";
}
}
Example of model file in which i have a function .
Class api_model{
function abc_model(){
$name="model function called in controller";
}
}
I want call the model function inside controller function to echo value of $name.
Can anyone suggest me how i can call the model function in controller in Pimcore.
Put your model files in /website/lib/ directory and register your "api" namespace in autoloader via /website/var/config/startup.php
Zend_Loader_Autoloader::getInstance()->registerNamespace([
'api',
]);
Then you should be able to use your model everywhere.
$model = new api_model();
$model->abc_model();
Note: You should follow PSR-4 (or PSR-0) specification to allow autoloader to resolve your classes.

Laravel custom view helpers stop working if using namespace

I have followed some tutorials to create some global helper functions to use in blade views.
I have created ViewHelpers.php file in App\Helpers folder. This file contains the following code:
<?php
class ViewHelpers {
public static function bah()
{
echo 'blah';
}
}
Here is my service provider which loads my helpers (currently just one file):
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider {
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
echo $filename; // for debugging - yes, I see it is getting called
require_once($filename);
}
}
}
I have added it to config\app.php in 'providers' section:
'App\Providers\HelperServiceProvider',
And now I call my helper in a blade view:
{{ViewHelpers::bah()}}
For now it works fine.
But if I change my ViewHelper namespace to this:
<?php namespace App\Helpers;
class ViewHelpers {
// omitted for brevity
my views fail with Class 'ViewHelpers' not found.
How do I make my views to see the ViewHelpers class even if it is in a different namespace? Where do I add use App\Helpers?
Another related question - can I make an alias for ViewHelpers class to make it look like, let's say, VH:bah() in my views?
And I'd prefer to do it in simple way, if possible (without Facades and what not) because these are just static helpers without any need for class instance and IoC.
I'm using Laravel 5.
You will get Class 'ViewHelpers' not found because there is no ViewHelpers, there is App\Helpers\ViewHelpers and you need to specify namespace (even in view).
You can register alias in config/app.php which will allow you to use VH::something():
'aliases' => [
// in the end just add:
'VH' => 'App\Helpers\ViewHelpers'
],
If your namespace is correct you do not even have to use providers - class will be loaded by Laravel.

Laravel 4.1 Facade Non-static method should not be called statically

I am attempting to create a facade within laravel 4.1. I have created the facade, service provider and the class, to no avail. I followed numerous "how to's" including the advanced video for custom facades on Laracasts. No matter how many times I try, I end up with the exception of Non-static method Custom\Helpers\Helper::doSomething() should not be called statically
Here is my code...
HelpersServiceProvider.php
<?php namespace Custom\Helpers;
use Illuminate\Support\ServiceProvider;
class HelpersServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('trial','Custom\Helpers\Helper');
}
}
HelpersFacade.php
<?php namespace Custom\Facades;
use Illuminate\Support\Facades\Facade;
class Helper extends Facade {
protected static function getFacadeAccessor()
{
return 'trial';
}
}
Helpers.php
<?php namespace Custom\Helpers;
class Helper {
public function doSomething()
{
return 'Hello';
}
}
I add the service provider to my app.php file and register the facade alias
'Custom\Helpers\HelpersServiceProvider',
'Helper' => 'Custom\Facades\Helper',
Then when I try to access it via a Static call (yes, I know it's not really static) or via the service provider directly I get the exception error.
Scratching my head on this one...
It looks like you have an incorrectly named class (or file):
HelpersFacade.php
class Helper extends Facade {
Additionally, your Helper class is in Helpers.php. Those need to match, also.

Categories