Which is better in codeigniter? Adding a function in a helper or adding a function in an extended base class - codeigniter

In a codeigniter project i have to do some set of stuff in one than one controller.
I code all that stuff in a function and now i need to call whenever necessary.
i think Writing this function in more than one controller is not good.
i have 2 options,
create a helper and write these function in that and include the helper in necessary controllers.
Since i have extended CI base controller (My_Controller) and most of my controllers are extended that controller, i can write this function to my base controller also.
I have confused which one is better, right way?
Which one will speed up the process?
Is the second way slows the site?

They are identical for all intents and purposes.
Using a helper allows you to make the code portable, so you can use it in other projects, or to be called from anywhere in the code base, in the case of a formatting function for example
If you were planning to put it in a controller, then MY_Controller is best bet

Just to help you on you endeavor what i do is: (this is just me)
If i need to use something in the views, i use a helper a custom one or built in.
If i want to do something on a controller that other controller will be using too and don't want it to mess up or crowd my controller i use a library (pretty much you can use a helper but i chose to use a library)
If i want to load lets say a method, to affect Globally or some of the controller i use the base controller. (you could also use helper or library)
The key is you are not restricted to one, choose the best that suits you, as the saying goes, there are many ways to skin a cat, but please don't skin a cat..

Related

Laravel Create Function to be used in different Controllers/in the same Controller

It's more a general question, I want someone to point me to the direction I should go.
1) FUNCTION FOR SAME CONTROLLER: I have two methods: Store and Update in the same controller. They both should contain some complex request validation (which I can't do via validator or form request validation because it's too complex). This means for me now using the same code twice in two methods... How can I take this code, create a function and use it in both Store and Update methods just with a single line, like:
do_this_function($data);
2) FUNCTION FOR DIFF. CONTROLLERS: I have another code which I use in many different Contollers. It transliterates Russian letters into Latin ones ('Сергей' = 'Sergey' and so on). How and where should I register this function to be able using it in different Contollers?
transliterate_this($data);
I have read something about helpers. Should I use them? If you an experienced Laravel develper and say so, I will read everything about them. Or, if you advice something else - I'll read about that.:) I just don't want to spend time reading about something useless or "not right way to-do-it".
Appreciate any help!
1) You could create a form request validation or you could just create a private function that would handle the validation and return the result.
2) You can create a helpers.php file, see here, and you put your translation function inside. Then you can call it from anywhere:
In a controller transliterate_this($data);
In a view {{ transliterate_this($data); }}.
You can do complex validation even inside a FromRequest. You can override the getValidatorInstance for example, or any other method from the base class to plug your validation logic on top of the basic validation rules. Else just consider making an external class to handle that complex validation and inject it in your controllers using Laravel's IoC container.
You should create a facade to provide that feature. Then you can easily use it anywhere (and additionally create a helper method for it if that makes you feel better). Something like Transliterate::toLatin($str)
everyone! Thank you all for great answers. But I have discovered that the problem was that I didn't know anything about Object-Oriented Programming.
(Ans I was working in Laravel:)).
After I took an Object Oriented Bootcamp from Laracasts, I started 'seeing' how Laravel actually works and I know can easily create methods inside classes and use them in other classes.
https://laracasts.com/series/object-oriented-bootcamp-in-php
(of course, you can read something else on OOP, but Jeffrey Way has really outstanding explanation talent!)

Basic on Codeigniter controller

I am new in codeigniter framework.I have some question.When we write some controller class then we call constructor.I am loading some library and some helper.I want to know what is the perfect way for loading this helper and library under construct class or under other functions.If i load everything in construct class then what is the disadvantages for it?if i use more controller class for one project then it is good or bad.Like i want to use some controller class for ajax functionalities,some for form submission,some for other sector.My english is not so good.Please help me.
For common libraries and helpers used by all functions of your controller try to load it in constructor or autoload. Except that for specific libraries e.g. payment gateway load inside the function.
How you use or how many controllers you are using depends upon your needs. But I would suggest you to build separate controllers for separate functions. Like admin for admin functions, users for user related functions, and so on. It build a user friendly URL too.
Well! everything depends on your requirements.
If you need any library , model or helper globally you can autoload it autoload.php.
It means the loading will be done on each request.
if you need any library , model or helper throughout your controller methods you can load them in constructor.
It means loading will be done on each method of controller.
if you need any library , model or helper for specific method you can load them in method.
It means loading will be done in method only.
For example let suppose you nees session and database library throughout your application so you can autoload it.
For a specific controller you need priviliges library so load it in constructor.
For email you need to send load email library in function.
These are only examples. You can explore SO to find more.
Loading takes time and performance. Not noticeable time by human standards, but time regardless. In order to cut of some slack to your server in the future, you do it a favor by only loading whatever is it you require for each page/controller method.
Used (almost) always
You can use application/config/autoload.php for things you almost always use. I usually include the helper url here.
Used (almost) always inside specific controller
Load it inside controller __construct. Don't forget to include parent::__construct();.
Used inside specific page
Load it inside method/function.
Used inside specific function
Load it at beginning or inside if-statement in function. You can load it numerous of times, it will only execute first time.

Using helper function inside a Core Class in CodeIgniter

There is a helper which I would like to use inside a core class, CI_Router (MY_Router, to be more accurate). In this custom router, I made some modifications to the original code, in order to be able to insert hyphens into my urls.
I have defined the helper on the autoload.php file, as usual, but it seems that I can´t invoque a helper function inside a class other than a view or controller.
Any ideas about how to handle this? My initial approach was to use a helper, so I can reuse it on any place I want.
TYVM.
Helpers are not instantiated until after the core, thus why it does not work.
You will either have to:
Duplicate the function in your MY_Router class, or,
Rethink why you might be using the same function in the Router that you use in a standard controller or view.
Option 1 is obviously easier, but might not be preferable depending on how bad your OCD is.
You could try getting the instance of the main CI object and setting it to a variable, then load the helper using that. Ex:
$ci =& get_instance();
$ci->load->helper('date');
I know that works in other areas, not 100% sure about any of the router classes.

Code Igniter App: Is-logged-in function: where to put

I'm building a simple login system for the CI based site and I I'm unsure of where to place my function:
is_logged_in()
// check if session logged in stuff exists
// if not check for cookie and reset from that
// return true or false
To start with I need to call this from some public pages so they they can display 'You're logged in as [blah]. Continue to members area'.
Would it make sense to put this in my login model, call it from my controller(s) and then simply pass the result (logged_in: true/false) to my views?
Mostly.
This might be a Model or it might be a Library issue. The question becomes how you are storing whether they are logged in. Personally, I generally put it in a Library which calls a specific Model, it seems less elegant at first, but realistically, I don't want my Model to know anything about my $_SESSION or my $this->session, one of which would be necessary if I wanted to have a good authentication system.
As to how to communicate with the view, there are a couple of ways:
Have it as a special variable passed to the view:
Bonus: It is the most obvious.
Detriment: You will need to place it into every single call to view. This means either you override your loader or you update all of your controls (might be gross).
Have it defined as a constant:
Bonus:By far the easiest if you have logic in the view.
Detriment:Constants are rarely the way to go, they are hard to debug, and it is not a very CodeIgniter way of doing things.
Have a helper function (literally a "helper" function)
Bonus:Universally accessible value which is relatively easy to debug.
Detriment:Requires a helper to know about a Library and/or Model (this is actually true of the built in form_helper, but it still opens up a proverbial can of worms) and it will probably be a one-function helper file.
Conditionally include a view from the controller
Bonus:It removes all logic from your view.
Detriment:You still need to make your controllers aware of the logic.
Personally, I am most likely to use #'s 3 & 4, but each has its advantages.

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Resources