Separate AJAX controller vs current controller? - ajax

I have a question more regarding style and organization that anything else. I often find myself having a single page (controller) that requires multiple ajax calls. Rather than creating a separate controller just for the AJAX calls because that would mean more controllers I just do the following:
class Management extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->protect->protect();
if ($this->uri->segment(2, 0) !== 0 && !$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
}
public function index()
{
$this->load->model('management_model');
$data['row_config'] = $this->management_model->getConfigRows();
$data['row_users'] = $this->management_model->getUsers();
$data['roles'] = $this->management_model->getRoles();
$this->tpl->head();
$this->load->view('management/scripts');
$this->tpl->body();
if ($this->messages->hasMessages()) {
$this->output->append_output($this->messages->display());
}
$this->load->view('management/manage', $data);
$this->load->view('management/current_users', $data);
$this->load->view('management/modals', $data);
$this->tpl->footer();
}
public function get_user_details()
{
$user = new \Auth\ASUser($_POST['userId']);
echo json_encode($user->getAll());
}
public function delete_user()
{
$user = new \Auth\ASUser($_POST['userId']);
$user->deleteUser(true);
}
As the index is the only page where I actually need to render a proper view, and the rest are ajax calls I just check the URI segment to see if something other than the index exists and then check if its an ajax request.
Is this bad practice? Should I separate the AJAX calls and the view controller?

Honestly, i don't think that there is a pattern on where you should add your ajax functions, especially in Codeigniter which is loosely coupled for most of it's structure.
In my opinion you should ask yourself the below, in order to find where you should place your ajax calls.
Are the returned data from the ajax call, related to the Controller i am already?
Will i ever use again the same method/functionality in another Controller or somewhere else?
Do i need the already defined constructor of the Controller, which i think i should place the ajax call?
Do i count on the DRY principle of software development?
Is my code flexible, reusable, etc.?
Each project has it's own philosophy and workflow. The design pattern and the data structure that you will decide you will follow, will solve most of your questions in your coding-style.

Your question is asking an opinion which is contrary to Stack Overflow's SOP. But I'll offer my opinion anyway.
Is this bad practice? I don't think so. That said, why make a controller larger than it needs to be? If your Ajax is handling the full CRUD functionality for some page then the controller could be quite large. You might be better served by a separate controller.
An Ajax call is a distinct request to the server - essentially the same as directing the browser to a separate page on some other browser tab. Why not make that request to a controller that is dedicated to Ajax? It could be argued that such a controller produces better "Separation of Concerns". That is good practice.
There is one technique to make certain this controller is only used when requested by an ajax call. A couple lines of code in the controller will make the determination.
class Some_ajax_handler extends CI_Controller
{
public function __construct()
{
if(!is_ajax()){
show_404();
}
parent :: __construct();
//if needed, do the rest of your construct here
}
public function get_user_details()
{
$user = new \Auth\ASUser($_POST['userId']);
echo json_encode($user->getAll());
}
}
The call to show_404(); ends with a call to exit() so you don't need a return; statement or else block in the controller. You can be confident that any method that gets called on this controller is indeed an ajax request.
On the other hand, if a controller's view uses Ajax to get the contents for a select input, or some other simple GET call, then creating a separate controller seems like overkill.
BTW, there is a CI library simplifying Ajax calls HERE that you might find interesting.
The one criticism I offer isn't about ajax but about your use of new which is contrary to the "Codeigniter way" for loading and utilizing other classes (libraries). But I guess that's a different topic.

Related

Can a Laravel POST route return a view instead of redirecting to another route?

I have seen/worked on lot of projects where a Laravel POST route looking like this:
Route::post('/some-url', [SomeController::class, 'someMethod']);
And the controller with its method which takes care of the route looking like this:
class SomeController extends Controller
{
public function someMethod(Request $request) {
// My Logic to do something with the post data - $request
return redirect("/some-other-url");
}
}
have always redirected to a specific URL after doing something with the POST data, by convention.
I would like to know, if after processing a POST request, if it's okay to just return a view like what we do with GET requests? I know it works, but is it just convention or are there any issues in doing so?
Eg:
class SomeController extends Controller
{
public function someMethod(Request $request) {
// My Logic to do something with the post data - $request
return view("somebladeview")->with(["result" => $result ]);
}
}
The pattern is called post-redirect-get, or PRG. It is convention because POST should be used for requests that change data, whereas GET should be used to simply display data.
If you return a view after a POST, the user can hit reload, and (probably unintentionally) change data again, eg buy something a second time. By using PRG, the user hitting reload simply reloads the last GET, which just re-displays something.
NOTE: There is some advice in the comments on your question to ignore this convention. I think that is unwise and dangerous, these conventions exist for good reasons.

CodeIgniter controller instantiation: when does it happen?

i'd like to know a details about when instantiation happens in CodeIgniter, specifically that of controllers.
Let's say i have a controller called Main which is structured like this:
class Main extends CI_Controller{
public $variable;
public function index(){
$this->load->view('home/body');
$this->variable="TEST";
}
public function run(){
do something with $this->variable;
}
}
Let's say i call on the browser localhost/index.php/main, thus instantiating for the first main the controller Main. Its default method index() simply loads an html page via load->view().
In this page, there's a button which makes an AJAX request to the same controller to use the method run(), using the url localhost/index.php/main/run.
At this point, will $variable be undefined? In other words, will the Main class be re-instantiated, or will the AJAX request use the same instance built before?
I understand your confusion. Often times with the singleton pattern in codeigniter it seems like variables will exist in perpetuity. That is not the case.
The AJAX load on run() is essentially a separate request (think of it as a page refresh). Any variables previously defined in index() or only defined in the request for index() will not be available.
You have 3 options to carry over variables from one call to the next: sessions, cookies, or database.

Laravel: Grab data from the Controller from inside a view composer

Atm I'm creating this view composer for fun. It is collecting .js filenames and then passing it to the layout to be linked. The filenames used depend on the current page. For example a lower ranked page like Slides, doesn't include ajax requests used in UserManagement. Please don't ask me why I would do this xD. Im planning to validate requests anyway. Just being bored.
Anyways, as I'm quite new to laravel I'm still looking for more efficient ways to do things.
Atm Im accessing the file names staticly. The Controller now looks like this
class Controller extends BaseController
{
public static $js_file_names = [];
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
In the pagecontroller I construct the filenames:
class SlidesController extends Controller
{
public function __construct()
{
parent::$js_file_names = ['ccs', 'ajax-updates'];
}
And finaly I retreive them inside the registered Viewcomposer like this:
(during development $use_filenames has all files as default)
public function __construct()
{
$filenames = Controller::$js_file_names;
if( !empty($filenames) )
$this->use_filenames = $filenames;
var_dump($this->use_filenames);die;
}
It all seems to be working fine, but the big question is, is there a better way to access controller data from inside a viewcomposer? Every time I try to google this, I get results like 'passing data to views' etc, which is not rly the problem.
Update:
Another idea I had is to store all the filenames to be used in an array inside the viewcomposer itself, and check if the current page exists in that array. This would keep the controllers cleaner.
Using a view composer doesn't really make sense in this situation. Since your controllers already 'know' which files they intent to share, you may as well just pass them to the view like so:
class SlidesController extends Controller
{
public function __construct()
{
View::share('user_filenames', ['ccs', 'ajax-updates']);
}
}
A composer is more for sharing concrete elements such as collections of users, a service provider or some other class instance, for example.

Should I call redirect() from within my Controller or Model in an MVC framework?

I'm using the MVC PHP framework Codeigniter and I have a straight forward question about where to call redirect() from: Controller or Model?
Scenario:
A user navigates to www.example.com/item/555. In my Model I search the item database for an item with the ID of 555. If I find the item, I'll return the result to my controller. However, if an item is not found, I want to redirect the user somewhere. Should this call to redirect() come from inside the model or the controller? Why?
No your model should return false and you should check in your controller like so:
class SampleModel extends Model
{
//Construct
public function FetchItem($id)
{
$result = $this->db->select("*")->from("table")->where("item_id",$id)->get();
if($result->num_rows() == 0)
{
return false;
}
//return result
}
}
and within your controller do:
function item($id)
{
$Item = $this->SampleModel->FetchItem($id);
if(!$Item)
{
redirect("class/error/no_item");
}
}
Models are for data only either return a standard result such as an key/value object or a boolean.
all logic should be handled / controlled by the Controller.
Models are not page specific, and are used globally throughout the whole application, so if another class / method uses the model, it might get redirect to the incorrect location as its a different part of your site.
It seems like the controller would be the best place to invoke your redirect because the controller typically delegates calls to the model, view, or in your case, another controller.
However, you should use whatever makes the most sense for your application and for what will be easier to maintain in the future, but also consider that rules do exist for a reason.
In short, if a coworker were to try to fix a bug in your code, what would the "reasonable person" standard say? Where would most of them be most likely to look for your redirect?
Plus, you said you're returning the result to your controller already... perhaps that's where you should make your redirect...

Codeigniter common templates

Let's say that I have a website that has 100 different pages. Each page uses a common header and footer. Inside the header is some dynamic content that comes from a database.
I'd like to avoid having to have code in every single controller and action that passes this common code into the view.
function index()
{
// It sucks to have to include this on every controller action.
data['title'] = "This is the index page";
data['currentUserName'] = "John Smith";
$this->load->view("main_view", data);
}
function comments()
{
// It sucks to have to include this on every controller action.
data['title'] = "Comment list";
data['currentUserName'] = "John Smith";
$this->load->view("comment_view", data);
}
I realize that I could refactor the code so that the common parts are in a single function and the function is called by the action. Doing so would reduce SOME of the pain, but it still doesn't feel right since I'd still have to make a call to that function every time.
What's the correct way to handle this?
One way I have been doing this is to extend the default controller class. You can read up on extending classes with MY_Controller in the user guide. Inside this extended class you can include something that you ALWAYS want to do, like render the page header template before the main content, or authorise a users access etc.
class MY_Controller extends Controller {
function __construct()
{
parent::Controller();
//code to always do goes here
echo 'Always print this comment';
$this->load->view('partials/template_start');
}
}
Then you can have your normal controller class extend THIS class by using
class MyControllerNameHere extends MY_Controller {
function __construct()
{
//setup here
}
function index()
{
echo 'Only print this bit when this method is called';
$this->load->view('partials/MYPAGENAMEHERE');
}
}
There are other ways of doing this, I use a mixture of the above and William's Concepts Codeigniter Template library. Do a bit of searching - there are a few solutions for you.
I had a similar situation. I created an 'includes' folder, and in there put a file that had the repetitive code from my controllers. Then in the controllers just include('/path/to/includeFile.php');
Don't know if it's the "correct" way, but it works well for me.
I ran across this after a search of their site. http://codeigniter.com/wiki/Header_and_footer_and_menu_on_every_page/ I'll review this page and its links, then post my thoughts.

Resources