Php use helper class

Php how to create helper class in laravel

Solution 1: There are many ways but simply you may try this: Or call a method directly: Which is equivalent to: You can also use something like this: Solution 2: You can use Laravel’s global helper: A better option may be to forgo registering anything in the container (which also means you can get rid of the service provider completely) and instead inject your class into the controller method: Laravel’s container will resolve your class and automatically inject an instance of the into it. Or use it this way: or Solution: You can add method and it will work.

Laravel get helper class from register provider

There are many ways but simply you may try this:

Or call a method directly:

app('mailer.helper')->doSomething(); 
$helper = \App::make('mailer.helper'); $helper->callSomeMethod(); 

You can also use something like this:

app('App\Helpers\MailerHelper')->callAction(); 

You can use Laravel’s global app helper:

app('mailer.helper')->sendFromContact(. ); 

A better option may be to forgo registering anything in the container (which also means you can get rid of the service provider completely) and instead inject your class into the controller method:

public function postContact(\App\Helpers\MailerHelper $helper) < $helper->sendFromContact(. ); > 

Laravel’s container will resolve your MailerHelper class and automatically inject an instance of the Mailer into it.

Php — How to create custom helper functions in Laravel, Custom Classes in Laravel 5, the Easy Way. This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.. Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and …

How to use laravel Eloquent model in helper class

If your model isn’t inside a namespace (the default setup with Laravel 4). Add this:

If it is inside a namespace:

use Your\Namespace\Category; 

Of course you can always directly specify the fully qualified classname . That means if your class has no namespace (exists in the global namespace) you use a backslash to make sure you reference it absolute and not relative to the current namespace:

And if the class happens to be in a namespace, just specify the full path:

$categories = Your\Namespace\Category::all(); 

You should be fine. You either declare it this way:

use Namespace\If\Any\Category; 

before your helper class and leave the rest as is.

$categories = Namespace\If\Any\Category::all(); 

Creating a Helper Class for Laravel Artisan Command, Laravel includes a variety of global «helper» PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient. Laravel documentation on Helper functions. There are lots of resources online to help you with this, I …

Laravel Redirect from Helper Class

You can add send method and it will work.

away('https://www.google.com')->send(); > > 

Php — Initialize helper class in Laravel, You can create helper class has static class so there no need to create instance of the class for example. so you can import class it in your controller using use keyword and access like. …

Читайте также:  Java using args main

How to make a class accessible globally in a Laravel application?

You should register your class as a singleton in the application container before you can use it. Otherwise, the app() function will create a new instance on every use. You can also give the instance a name in the container, this way, you don’t have to create your own global function.

In your AppServiceProvider.php :

$this->app->singleton('settings', function ($app) < return new \App\Helpers\SettingsHelper; >); 

And now you can use your class with:

app('settings')->put('test', 'test2'); dd(app('settings')->all()); 

Create a service provider php artisan make:provider HelperServiceProvider

Then in the register method do something like:

Make a singleton in a provider, example AppServiceProvider.php .

use App\Helpers\SettingsHelper; $this->app->singleton(SettingsHelper::class, function ($app) < return new SettingsHelper($vars); // create your class with the vars you need >); 

Everywhere in your app there can only be 1 settings helper and you can get it like so.

use App\Helpers\SettingsHelper; app(SettingsHelper::class); 

Php — Custom helper classes in Laravel 5.4, > I want to be able to do something like this in my blade templates: How to create custom helper functions in Laravel. 3. Laravel custom view helpers stop working if using namespace. 1. Autoload …

Источник

Php use helper class

Many Yii users ask how to create helper classes and functions, and though there are numerous approaches spread out among the forum and wiki articles, this Tutorial tries to bring it all together in one place.

Creating helper classes ¶

You might wish to create helper classes for several reasons:

  • to extend and customize existing Yii classes
  • to create classes to implement business objects not covered by Model objects
  • to reuse helpful classes from other projects

Yii handles this particularly efficiently by smart use of Autoloading; when an unknown class is used, Yii automatically loads a file of the same name, but with a .php extension.

One only need create a class file in the components/ directory, define the class itself, and Yii will find it:

 // protected/components/MyClass.php class MyClass  

Then, if the class name MyClass is mentioned (including the use of static references), Yii loads it automatically.

IMPORTANT: Autoloading requires that the class name and the filename match exactly in spelling and case; being off just a little bit will produce an error. If you define class MyClass in the file `Myclass.php, you will receive the error:

PHP ERROR include(MyClass.php): failed to open stream: No such file or directory 

Rename the file to MyClass.php , matching the class name, to fix this error (unless this is an autoload path issue — see final section).

Note: Because Windows filesystems maintain but do not respect case, misspellings like this may still work, but the application will break if ported to Linux/UNIX.

Creating helper functions ¶

Almost all experienced PHP programmers have written small helper or utility functions, ones that are essentially standalone (not related to any particular objects), with string functions being particularly popular.

Though it’s possible to create your helpers as static functions inside an autoloaded class:

 // protected/components/Helpers.php NOT RECOMMENDED! class Helpers < // does the first string start with the second? public static function startsWith($haystack, $needle) < return strpos($haystack, $needle) === 0; > . 

but this is tedious: it’s much more convenient to use regular ordinary functions to do this, and it’s easy to achieve in Yii (though it does not involve the autoloader).

1. Create helpers function file ¶

I usually define helpers in protected/components/helpers.php :

 // protected/components/helpers.php function startsWith($needle, $haystack)  < . >. 
2. «Require» the helper file in the config file ¶

Now that the helpers file is in place, we need a place to include it early in the application so that it’s available throughout.

Though Qiang recommends putting it in webroot/index.php , I recommend putting it in the protected/config/main.php file instead, mainly because I usually want to apply the same treatment in protected/config/console.php for console-mode applications. Doing the same change in the same way feels cleaner.

Add the require_once directive near the top of the file so that the config file itself can get the benefit of your helper functions.

 // protected/config/main.php require_once( dirname(__FILE__) . '/../components/helpers.php'); . 

This done, any part of the application can use the helper functions defined here:

Note that Qiang has written about this topic as well, though from a somewhat different angle: Qiang’s wiki article

Setting/Verifying the Autoload Path ¶

Unlike other frameworks that actually preload your runtime classes — which can be a substantial performance hit — Yii performs autoloading only when the classes are needed.

You define the locations to autoload from in your configuration file in the import section:

// protected/config/main.php return array( . 'import' => array( 'application.models.*', 'application.components.*' ), . 

Yii notes all the files found in these directories and associates them with classes of the same name. If one of the classes is later needed, the file is include d directly, which provides the class to the application.

Some notes about autoloading:

  1. application. is an alias for your protected/ directory
  2. None of these files is actually loaded by PHP unless the contained classes are actually requested by the application; there is very low overhead in setting up autoloading
  3. If you wish to use the same autoload paths in console applications, set the same imports in protected/config/console.php
  4. Autoloading doesn’t search subdirectories: if you want to autoload the protected/components/mystuff/ folder, use ‘application.components.mystuff.*’ in addition to ‘application.components.*’

Multiple classes in one file ¶

It’s possible to include more than one class inside a file, though this is only useful in some narrow circumstances.

Autoloading is only done when the desired class name matches the filename, but if a file contains a «main» class used by an application, but it in turn defines minor helper classes that the application won’t call directly, this is perfectly legitimate.

Since the application only requests the primary class, that file is autoloaded upon use, but everything in a file is loaded into PHP during include time. This brings the support functions along with it even though the application may be unaware of these goings-on.

Manual autoloads ¶

The usual autoload path does not pull from the zii framework hierarchy, which is why full application paths must be used when requesting widgets:

$this->widget('zii.widgets.grid.CGridView', array( . 

This tells Yii to find the file via a specific application path, which is typically from within the framework source code directory itself.

But if one wishes to extend the CGridView class, we have to take the step of importing that specific name before we can use it:

 // protected/components/MyGridView.php Yii::import('zii.widgets.grid.CGridView'); class MyGridView extends CGridView < . 

Curiously, the import() statement does not actually load the file: instead, it sets up an autoload so that the provided filename will be loaded as soon as CGridView is referenced, which it is just two lines later.

This means that any application can now use MyGridView the same as any other class, without an application path:

$this->widget('MyGridView', array( . 

Источник

Helper Class in PHP

As a rule of thumb, helpers should contain functionality that is common but has no special designation under the overall architecture of the application.

// Helper sample // class ConversionHelper < static function helpThis() < // code >static function helpThat() < // code >> // Usage sample // class User < function createThings() < $received = ConversionHelper::helpThis(); >> 

Solution 2

Helper classes are usually a sign of lack of knowledge about the Model's problem domain and considered an AntiPattern (or at least a Code Smell) by many. Move methods where they belong, e.g. on the objects on which properties they operate on, instead of collecting remotely related functions in static classes. Use Inheritance for classes that share the same behavior. Use Composition when objects are behaviorally different but need to share some functionality. Or use Traits.

The static Utils class you will often find in PHP is a code smell. People will throw more or less random functions into a class for organizing them. This is fine when you want to do procedural coding with PHP

Moreover, every Class that use Helper class must create a helper object is a code smell. Your collaborators should not create other collaborators. Move creation of complex object graphs into Factories or Builders instead.

Solution 3

Instead of creating static class , you should just write simple functions , and include that file at the index/bootstrap file (you can even use namespaces with it).

It should be:

namespace Helper; function split_word($text) < . function split_char($text) < . 

There is no point wrapping it all up in a class. Just because you put it in a class doesn't make it object oriented .. actually it does the exact oposite.

Solution 4

You could create a class with static methods.

You could also namespace a bunch of functions with a namespace , but I think the former is preferred.

Solution 5

Use public static methods in the class as such:

/* Common utility functions mainly for formatting, parsing etc. */ class CrayonUtil < /* Creates an array of integers based on a given range string of format "int - int" Eg. range_str('2 - 5'); */ public static function range_str($str) < preg_match('#(\d+)\s*-\s*(\d+)#', $str, $matches); if (count($matches) == 3) < return range($matches[1], $matches[2]); >return FALSE; > // More here . > 

Then invoke them like this:

If in another file, use the following at the top:

require_once 'the_util_file.php'; 

Источник

Оцените статью