How to create and load new helper in CodeIgniter 4 - php

i want to create new function in helper, but it still failed :
Call to undefined function
i save my helper at app/Helper/Text_helper.php using namespace App\Helpers;
and load helpers on BaseController using protected $helpers = ['text'];
Reference : https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers
but it's still not working

It's not mentioned in documents but remember to add a suffix _helper to filename of your helper otherwise it will not work in codeigniter 4.
For example if you have created a helper xxx.php, change it to xxx_helper.php.
To load a helper you can use helper function (Like: helper('xxx.php');) or add it to $helpers array that is an protected property in BaseController

If your idea is to "extend" (replace) a function on the stystem/helpers/text_helper note the lowercase in the name of the file, you have to respect it.
Also, the helper doesn't need a namespace... the helper loader will search for it.
The helper() method will scan through all PSR-4 namespaces defined in app/Config/Autoload.php and load in ALL matching helpers of the same name. This allows any module’s helpers to be loaded, as well as any helpers you’ve created specifically for this application. The load order is as follows:
app/Helpers - Files loaded here are always loaded first.
{namespace}/Helpers - All namespaces are looped through in the order they are defined.
system/Helpers - The base file is loaded last
the namespace will be used to load a helper on other location, for example:
helper('Libraries\MyFunctions');
as long as that path can be found through a namespace that has been set up within the PSR-4
Reference:
https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers

You need to load the helper into the app/Config/Autoload.php and still not work then please try to run composer dump-autoload

Related

Why not set the method of the function helper as the default method of CI [duplicate]

I just downloaded CodeIgniter 4 from their official GitHub. They changed a lot from CodeIgniter 3. I want to use base_url() function in the view and for that, you need to load URL helper and in CodeIgniter 3 I autoloaded it in config/autoload.php file. But now they have entirely changed the structure of config/autoload.php file in CodeIgniter 4 and it is very confusing to me.
You can still use the base_url() function in your views in CodeIgniter 4 by using below code in your constructor of controller helper('url');
If anybody who used CodeIgnter 4 knows how to autoload helper functions like url by modifying config/autoload.php file please help me.
CodeIgnter 4 is currently in developing phase so many features are still not available. The answer is you cannot autoload helpers or libraries in autoload.php file in codeigniter 4.
I know this is a feature used by many of us but autoloading every thing will decrease site performance so may be developer team decided to drop this feature.
from Codeigniter 4 Documentation:
You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it.
https://bcit-ci.github.io/CodeIgniter4/general/helpers.html
Add your helper to the array in BaseController.php file like this:
protected $helpers = ["form"] // BaseController.php:29;
Just add name of helper(s) you want to load in
protected $helpers = [] in
/app/Controllers/BaseController.php
CodeIgniter4 will load those helpers automatically.
For example:
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = ['cookie','date']; // <=== this
For Future Reference
Since there is no autoload in autoload.php you have to load all helper files by itself. Unlike global load in CodeIgniter 3.
How to load
public function FunctionName()
{
helper(['form', 'validation']); # before retun to view.
#rest of your code
}
Do we need to load this into each and every method(s)?
Yes. Since I play around it I'm unable to load helper file globally.(2018-2-07)
Step 1
Create helper on App/Helpers. Example : alert_helper.php, MUST ending with _helper
Step 2
Load helper on Constructor or Method. helper(['alert']);
Step 3
Use helper
DONE
UPDATE CodeIgniter 4.3+
CodeIgniter 4.3.0 has finally added this feature.
Just edit the app/Config/Autoload.php file and add the helpers you need globally.
public $helpers = ['repository_helper', 'serializer_helper'];
https://codeigniter.com/user_guide/general/helpers.html#auto-loading-helpers

how to use another controller function without extends in our controller

how to use another controller function without extends in our controller
$this->load->library('../controllers/controllername');
already used
it is giving error =
Unable to locate the specified class: Session.php
Well you are not supposed to do that. If your controller uses repeatable logic, you should make class (Service for example), put the re-usable logic into it and call it in your controllers.
You can't use another controller function inside the controller. You can archive this in these two ways.
Create a Helper class
Create a generic model.

ZF2 change extends class

The answer to my question ZF2 FormInput to show error class on validation fail is to create my own form view helper, overriding the render function. While this works beautifully for elements being rendered using forminput, it doesn't help on elements that inherit from forminput. For example, FormCheckbox inherits from forminput but not MY forminput:
<?php
namespace Zend\Form\View\Helper;
//...
class FormCheckbox extends FormInput {
//...
}
In this case I would need to create ANOTHER form view helper for formcheckbox exclusively to extend MY forminput. And again for any other view helpers I want to include (formdate, formemail, formpassword, etc).
Instead of creating multiple view helpers is it possible to create a single view helper and tell ZF2 to use that in all calls to the original view helper when made by a ZF2 view helper?
i.e. \Zend\Form\View\Helper\FormCheckbox would extend \RPK\Form\View\Helper\FormInput, which would extend \Zend\Form\View\Helper\FormInput.
A solution I can think of, is rewriting a part of the autoloader.
In the autoload function, you add an extra check to check if the requested class is \Zend\Form\View\Helper\FormInput, and if that's the case, you load your custom FormInput.
In your own FormInput you don't extend the Zend FormInput, but you create a copy of it, and modify the parts that are needed to be modified.
Unless ZF2 is using dependency injection for it's form helpers, this is the only way I can think of (without altering the base library code).
What I have used are view partial. With partials you can define your own html for every input-element and you have access to all attributes and messages (e.g error-messages) of the input-element:
in your partial phtml:
<?php
$options = $element->getOptions();
$t = $this->t();
$value = $element->getValue();
$messages = $element->getMessages();
$attr = $element->getAttributes();
you can use a partial like this:
$this->formRow($form->get('myelement'), null, null, 'mypartial');
I am using composer to install ZF2. As composer is generating my autoload functions I can specify an autoload path in the composer.json file:
"autoload": {
"psr-4": {
"Zend\\Form\\View\\Helper\\": "vendor/rpk/Rpk/Form/View/Helper"
}
},
This will search in my vendor folder for the class before looking in the zend folder.
This does not let me extend the FormInput, but calls my FormInput in its place. Calling extends on my FormInput puts the app into an infinite loop, so we need to copy the contents of FormInput into my class and make the changes there.

invoking an action helper

I have a directory structure such that I have three directories inside my root directory, namely application, public and library.
Now, inside the library directory, I made a directory Custom, inside which I have a directory Controller, inside which I have a directory Action, inside which I have a directory Helper, and this directory contains a php file named 'LinkTo.php'. Inside this file, I have a class named Custom_Controller_Action_Helper_LinkTo which extends Zend_controller_Action_Helper and provides with a simple function called linkTo($inputString)..which outputs the url as per the input string parameter. But, I get this error "Action Helper by name CustomControllerActionHelperLinkTo not found " even though I have mentioned 'Custom_' in autoload namespaces in my application.ini, and have also taken care of include paths in my index.php.
Please help! How does one make an action helper like that and invoke it?
Did you specify path for the custom Action Helpers ?
You can do this in your application.ini, add following line:
resources.frontController.actionHelperPaths.Custom_Controller_Action_Helper_ = "Custom/Controller/Action/Helper"
After you specified path for your custom helpers, you need to initialize them for the later use. This can be done in Bootstrap:
protected function _initHelpers()
{
Zend_Controller_Action_HelperBroker::addHelper(new Custom_Controller_Action_H‌​elper_LinkTo());
}
If you want to use helper as a method of the helper broker, for instance:
$this->_helper->LinkTo(); your custom helper should implement direct() method.

CodeIgniter helper in the view

Is it a good workaround and would it be possible to use helper classes in the view, in CodeIgniter. I have a situation when I have to extract with regulars expression from a text couple of strings and generate outputs on matches. I would not like to do this directly in the view and I would like to use for this purpose a helper.
application
--view
---myview.php
and here I should call the helper and return results
for example I want to extract from the text the type of processor, than I pass the text and get returned the processor type. This one is needed because all the data in the view are generated by an API dynamically.
echo $myhelper->processor($text);
CodeIgniter's user guide explains that helpers can be loaded and their function used in views.
CodeIgniter does not load Helper Files by default, so the first step
in using a Helper is to load it. Once loaded, it becomes globally
available in your controller and views.
However it is not best pratice to load a helper in a view, so you could either auto-load the relevant helper, or load it in your controller(s).
A helper can be loaded anywhere within your controller functions (or
even within your View files, although that's not a good practice), as
long as you load it before you use it. You can load your helpers in
your controller constructor so that they become available
automatically in any function, or you can load a helper in a specific
function that needs it.
So, using helper functions in a view is fine, although it is encouraged that the helper is loaded in a controller, or auto-loaded.
get_instance()->load->helper('HELPER_NAME');
Just load the helper in your controller, then
$this->load->helper('MY_common_functions');
$template['content'] = $this->load->view('your_view');
In the view call your function name directly. In this case I called my convertor function
echo convertor($params);
It is standard in Codeigniter 4, always load Helper function before to use it, Either in Controller or Views.
In Codeigniter 4 If we declare Helper function in Controller's __construct method like:
<?php
namespace App\Controllers;
class NewsEventController extends BaseController{
public function __construct(){
helper('form');
}
Than this Helper function will available in all controller functions & views of that controller. Example a view file with 'form' helper function 'set_value()' in an input field like:
<input type="text" class="form-control" name="title" value="<?= set_value('title') ?>" >

Categories