Codeigniter - reusing controllers? - codeigniter

I am trying to code my first codeigniter project. I have a login controller which basically filters the data inputed and calls a model function that checks if the user is found in the database.
What I am trying to do is reuse this controller on the index page. So basically I want to be able to do user login on the index page or on the normal controller page (index.php/login/) without code duplication.
I'm sure there is an easy way to do this, but I'm not sure what the best solution is. Make it a library?
Thanks!

For this I would simply make the form in your view post to the login controller.
As a more generic way to share code and logic throughout your application, take a look at this article:
CodeIgniter Base Classes: Keeping it DRY
You basically give each of your controllers a "type". Being logged in could be a criteria of one of your base controllers, which saves you trying to directly access any of your controllers which is bad mojo.

You can try creating a form on the index page and submit it to index.php/login/. This way you won't need two entry points.

Just do the same as you have done for the login View, specify the same action attribute of the form to the index View, and it will be sent to the same login controller with no need to create the two login controllers. You might want to append a query string in the action attribute of the form to distinguish from which View the request has come.

Related

Passing data from one view to another in Laravel

I have a Controller that parses an XML and returns a view with a list of names and URLs.
return view('view_1',compact('myList'));
View_1 will have a form with parameters method="POST" action="goToView_2"
Then I get some information from my view_2 through a POST, but I still want to keep $myList so that view_2 view uses it aswell.
How do I pass $myList from the first view to the next through a controller?
It sounds like you're trying to have multi-step form of some kind.
I would store the data in the session and easily access it in the second controller or in the view (although not recommended).
https://laravel.com/docs/5.4/session#using-the-session
PS. I personally love using the global session helper.

Convention for a controller that generates a view from several models

In Sails.js, a route is set up against a controller method which can render a view. For the most part, this is straightforward, i.e. you could set up a GET /users route that points to UserController.find (which is usually set up automatically anyway).
However, say the home page of a blog renders the 10 most recent posts in the main section and a column with a list of authors and categories. The controller method has to fetch posts, authors, and categories before rendering the view and sending it back to the client. Clearly, a method like this doesn't really belong in PostController, AuthorController, or CategoryController.
What's the best thing to do in this situation? Create a controller for rendering views that rely on data from multiple models? Is there a good name for such a controller?
Thanks!
What I would do (this is purely opinion-based) is creating a PageController and create an action for each page you'd want.
For your home page example you can create a home action, get whatever you need and then render it with res.ok() (if everything is fine).
Another option would be to use Sails as a pure API and use HTTP requests (Ajax) or sockets to get your data in JSON. If you want to do so, I'd advise you to use a front end framework such as Angular, Ember, React...
By the way you could also create actions rendering HTML in your existing controllers and create a route to hit them through Ajax requests and just print them in your page. I'd prefer the 2nd solution because it takes full advantage of the Blueprint API (you don't need new controller or action whatsoever).
As Yann pointed out, this answer has to be a little opinionated. It seems that you are using the views system and not building a single page application. For the home page, I would go for an IndexController.js file with a home(req, res) action.
// api/controllers/IndexController.js
module.exports = {
home: function (req, res) {
// Retrieve all the information you need
// Take care about managing the asynchronous calls before rendering the view
return res.view('homepage');
}
};
Declare the route
// config/routes.js
module.exports.routes = {
'get /': 'IndexController.home'
}
Create the view in views/homepage.ejs.

Symfony Good practice : How to embed several forms for a single entity, handled by different controllers

I'm working on an application with Symfony 2 and I'm quite new with this framework.
I would like to create a page that represent an user profile on which users can update their personal information, set up an profile picture and a cover picture.
I've written the code for the User class and the template. For both profile and cover picture i'm using ajax with formdata to send images to server.
The other fields (username, email, etc.) are also sent with ajax, but all three parts (profile picture, cover picture, textual fields) of the form have their own submit button.
My problem is about creating controllers and forms.
Should I create a controller for rendering the profile page and then one controller for handling the form ?
Should I create a single form for all fields on the page or create three separated forms that would be handled separately ?
Should I use formbuilder to create form(s) and in the case of there are more than a single controller, how to retrieve the form created in the first controller in the others to proceed validation
Or maybe am I wrong from the beginning ... ?
I can provide my current code, but I don't think it can be useful since my User class and my template are very basic and I'm stuck on writing the rest of the code ; and I prefer knowing the "good" way of doing it before writing too much trash code.
You can have many form and validate them in one controller:
public function updateAction(Request $request)
{
$form_one = $this->get('form.factory')
->createNamedBuilder('form_one', 'form')
->add('user_picture', 'file')
->add('submit', 'submit')
->getForm()
->handleRequest($request);
// Next form ...
if ($form_one->isValid())
{
// Save user picture
$data = 'user picture saved';
}
// Other forms validation
return new JsonResponse(data);
}
Make sure to create the same forms in user profile controller view.
Should I use formbuilder to create form(s) and in the case of there
are more than a single controller, how to retrieve the form created in
the first controller in the others to proceed validation
You could make formType, like in this example, there is RegistrationType.
Then use formType in different controllers.
Then you could validate form from entity(or whatever doctrine,propel or whatever you are using) using entity validators
You could also check generator bundle, specially Generating a New Form Type Class Based on a Doctrine Entity
Symfony best practices say to use custom form type classes for forms
link
I always use seperate controller actions for seperate forms. Code becomes more organized and is easier to debug. And I have had issues/bugs with multiple forms in same controller.

Symfony2 and filter, right strategy

I'm asking what is the best strategy for filtering with Symfony2.
I want to filter a table of entities (hotels). This filter should allow me to :
choose hotels with or whitout email, with or without web site etc.
choose hotels based on state and/or city (relation OneToMany)
choose what information I want to display on the table with checkboxs (for example display "email adress" on the hotel table, but do not display "tel" or "web site").
First I think to build the filter form on the HotelController. When the filter is submitted, I had a FlashBag for every $_POST sended, redirect to the same page, and if there are FlashBag I send cookies to the $reponse. Then I display the table filtered with data who are on the cookie.
But I dont't really like this, cause I had a very big indexAction() on the HotelController, and I think it'as not really clean to change $_POST to FlasBag to Cookie, is it ? I do this redirection, cause by refreshing the page, data are not posted again.
I'm also asking a question, to prevent a too big IndexAction() method, can I put some code to another method, for exemple a method PostToFlashBag() and another FlashBagToCookie(), or every method on a Controller has to end with the word "Action" and must be accessible with the router ?
Then, I think to another thing : had an entity "Filter", with every row I need. For exemple "WithEmail", "DisplayTel" etc.. Then I can build a FilterType easily, and update the Filter entitie, to redirect to the same page (again, to prevent reposting data if the user refreshes the page). Finally, I can display the table with the object Filter, with a method on the HotelRepository.
That seems great, but I'm a little worry because the filter entity will only have one entry, and I have to find the Filter(1). Due to MVC, is it correct to have a model with only one entry ?
What strategy would you choose (maybe another one) ? I'm interesting to learn good practice with MVC and Symfony2 devloppemnt.
Having a dedicated model class - let's call it Filter - that will receive the values input by the user, is definitely the way to go.
More over, use the Symfony2 form on this input, so you can have validation, and be sure that the withEmailis trully a boolean, etc. From you Filter, build you SQL/Doctrine query and return what your controller have to return, be it a view, or raw datas.
You can have any method you want in a controller. After all, controllers in Symfony2 are plain old PHP objects. They only have to implement ContainerAwareInterface. Usually they inherits Controller, but this inheritance only brings some proxy methods, like getDoctrine or render.
The only convention is that methods which are used as route must end with Action

MVC in yii: how to build pages with several actions belonging to different models

I would like to know how you should write website pages that use for example 3 models and several actions on them.
Because there is usually only a controller involved with a page call and only a special action.
For example:
there should be a page which displays a group of people, and on that page I can edit the peoples names and assign new people to the group and i can add people as new managers of a group.
Does this page need its own controller or how do I program such pages?
Using your scenario, here is how I would set things up:
The controller you'd use for all related actions would be 'Group' (in Yii, 'ControllerGroup')
For your main page that displays the group of people, you could make an action in your Group controller called 'manage' (in Yii, the method name would be actionManage). Assuming you aren't going an Ajax route, for each person on the manage page you may have a link to edit that person. The links would point to the 'update' action. For adding, you'd want an action 'add'.
Your models involved would likely be User, Group, and UserGroup and you'd use them as necessary in any controller you have.
Actions can belong only to controllers. In each action you can work with any models of your application. In your case you must create a UserController and a list of actions (e.g. actionViewList, actionEdit, actionAssignToGroup).
Check this for more information: Yii Controller

Resources