CodeIgniter: Decision making for creating of library & helper in CodeIgniter - 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.

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!)

2 small questions regarding Laravel facades

I know it's an issue with a lot of debate, but there are two aspects about it that I haven't seen much reference to and would like to know the answers to:
We're using static functions all the time - I'm sure no one will ever stop using dd() helper for example, but obviously even pure PHP static functions like json_encode() or array(). Why doesn't it make sense to see laravel classes behind facades as similar helper functions and not as class dependencies?
More than that, many times we're using those dependencies in a narrow control flow (or conditions) inside the method and the class\method is truly not necessarily dependent on those helpers all the time (for example user class used only if user is authenticated etc.)
In his response to this debate, Taylor Otwel himself said that the use of facades may lead to responsibility bloat in your classes meaning we might be tempted to write classes\methods that do too much and not separate them - but I don't understand how using facades instead of injecting all those classes in the contractor or method is different in terms of responsibility - from what I understand it's just a change in where you "declare" those classes - in the method signature or inside it (I understand that has a lot of differences, but don't see one in class responsibility matter). Can someone explain this?
Bottom line I'm asking this because obviously I'm all for facades when they serve as helpers and not as a core part of the class\method purpose, and I want to know I'm not the only one... I'm mostly anxious of having to write every little piece of helpers I'm using as dependencies in my classes.
Thanks!
Since this discussion is swathed in controversy, I'll make this short and just answer directly the two points you raised:
The native PHP json_encode function can be considered a helper because it's idempotent. In short, it has no dependencies, and has a predictable output. So for example the date function is not a helper function. Many people shy away from it for that reason, and use the DateTime class instead.
What Taylor means by responsibility bloat is that since you're not declaring your dependencies up front, you don't realize how much your controllers do. If you're forced to declare your dependencies up front (via injection), you're more likely to realize when your controller has too many dependencies, and abstract some responsibilities into their own class.
Again, note that I'm not offering an opinion here; too much controversy around it. I'm just clarifying what you've asked so that you can form your own informed opinion.

Codeigniter: Fat models vs Libraries

i am new to codeigniter, the question # headline has been asked before, but i'm not yet convinced.
If i am creating a registration and login system, it would include functions such as
(login(),forgot_pass(), remember_me,register(),etc).
So where is it best to keep their definitions:a model(fat model)or a super model or in a different library altogether, in the latter technique it would be less of object oriented.
As a library you just need to load the library and you can use it in any controller, model or view.
$this->load->library('my_library_name');
$this->my_library_name->do_something();
As a model, you could do the same as the library:
$this->load->model('my_model_name');
$this->my_model_name->do_something();
Other methods, like helpers, are not practical. I did it as a library. I just liked it this way.
To answer to your question: do as you see fit or as you like it.
LE: Take a look at TankAuth for CodeIgniter, maybe it will get you an idea.
As machineaddict said when you need to call your function in your library file you need to load it first.
$this->load->library('you_library_name');
$this->you_library_name->function_name();
Additionally, if you want to use it as global function just put your function out of the class. Once the library is loaded, you can just use your function() without $this->you_library_name->function_name();

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

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..

In Joomla, where should I put my classes that calculate?

I'm working on a joomla component that includes building a schedule. On any given day it needs to look at a set of rules (day of the week, date of the year, type of event) and return all of the possible start times. It would make sense to have a class that calculates these things, but I'm not sure it fits in the model or controller (and certainly not view) categories. Am I supposed to create a com_myproject/lib (or similar name) and have joomla auto-load the classes?
I'm new to joomla and started with the framework/project provided at http://docs.joomla.org/Building_Joomla_Extensions_with_Apache_Ant.
You should create a helper class. Have a look here for an example, albeit it is for a module, but the same concept applies.
You might want to start off with Developing a Model-View-Controller Component - Part 1 tutorial and work your way through that by hand. Using Apache Ant to learn how write an extension is like taking a canon to shoot fish in the barrel. It can be done but probably not the best way of doing it.
The Joomla! MVC pattern is very peculiar and difficult to understand. I don't quite understand it myself. I was advised on the developer email list to look at how other components are put together. Guess what? All the other developers do it differently, with some of the bigger components looking like spaghetti code in their organization.
The bulk of your component code should be in the controller, either as part of the controller class or a separate class file that's imported in. You don't need a separate library directory unless you're working on a big component with multiple class files. This Joomla! thread might be applicable.

Resources