I'm a newbie to codeigniter and I'm attempting to write a function that would basically save a name and url to session data whenever you visited a certain page, then report it back in a small widget on the screen.
It's supposed to work as a kind of history function for what pages have been accessed and in what order. So far when working with test data it works great! however I'm trying to figure out how I can call the "add" function on each page that is visited, so we can supply the name and url of that page that was visited. Is there any way to do this? Or is there any way to report back a set of variables such as a name and url for a page after you visit it?
For example: say I visit page1, page2, page3, and page6 and I want each of those to show up in my history function. On each of those pages I would load the history view, and I would want to call the history's controller function "add(name,url)" and fill it in something like this:
add('page1','page1.php')
But I know that you're not supposed to access the controller from the history because that's not the way it's supposed to be done, however I cannot think of any better way to do this. Any help would be appreciated.
I don't know why dont you call this on every controller.
but if you want to call a function of the current controller, you have to get the instance of the current controller this way:
<?php
$CI =& get_instance();
$CI->method($param);
?>
the easiest way to do this would be to put a method in the constructor of your class. that way it will always run first thing, no matter what you are doing. remember that anything you can do in the controller -- sessions, validation, etc -- you can do in a model.
function __construct() {
parent::__construct();
// load model that has page tracker methods
$this->load->model( 'pagetracker_m' );
// call the method to track the pages, and have it return the results
if ( ! $this->history = $this->pagetracker_m->_trackpage(); ) {
echo 'Error getting history ' ; }
} // end construct
function something() {
// pass history to $data, then use echo $history->firstpage, etc in view
$data['history'] = $this->history ;
// call your view etc
}
Related
I'm currently creating an app with Codeigniter and i came up with this issue (and it's not the first time to be honest).
What i want is to set a value in a global variable in function "foo()" and the access it through function "bar" (which is called through ajax call from client side).
In short, i want this variable to be full when the user has visited the page (sth like a session).
Here's an example code of my controller and what i'm trying to achieve:
class Groups extends CI_Controller{
private $page_id;
public function foo($slug = FALSE){
$this->load->model('some_model');
$info = $this->some_model->get_info($slug);
$this->page_id = $info['page_id'];
}
public function bar(){
$this->load->model('some_model');
$info = $this->some_model->get_some_other_info($this->page_id);
//Some code in here
}
}
Any suggestions or best practices on achieve that?
I've tried searching the internet on that but i couldn't find something to start with. So if you have any suggestions on where to look at, feel free to do it!
Thanks
If i understand it right you will have 2 calls. One will be at page load where you want to store something and after that there will be an ajax call that will retrieve what you have stored. Because the 2 script loads are different you can only do it by storing the data to one of them: database/session/cookie/html session or localstorage.
Can't say anything about best practice because i dont know what you want to store and for how long so need a bit more info about your code (im guessing you want to store the "page_id"?).
I am in the process of learning the MVC pattern and building my own lightweight one in PHP
Below is a basic example of what I have right now.
I am a little confused on how I should handle AJAX requests/responses though.
In my example user controller below, If I went to www.domain.com/user/friends/page-14 in the browser, it would create a User object and call the friends method of that object
The friends method would then get the data needed for the content portion of my page.
My app would load a template file with a header/footer and insert the content from the object above into the middle of the page.
Now here is where I am confused, if a request is made using AJAX then it will call a page that will do the process over, including loading the template file. IF an AJAX call is made, I think it should somehow, just return the body/content portion for my page and not build the header/footer stuff.
So in my MVC where should I build/load this template file which will have the header/footer stuff? ANd where should I detect if an AJAX request is made so I can avoid loading the template?
I hope I am making sense, I really need help in figuring out how to do this in my MVC I am building. IUf you can help, please use some sample code
/**
* Extend this class with your Controllers
* Reference to the model wrapper / loader functions via $this->model
* Reference to the view functions via $this->view
*/
abstract class Core_Controller {
protected $view;
protected $model;
function __construct(DependencyContainer $dependencyContainer){
$this->view = new Core_View();
//$this->view = $dependencyContainer->get(view);
}
public function load($model){
//load model
//this part under construction and un-tested
$this->$model = new $model;
}
}
user controller
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
//GET data from a Model
$profileData = $this->model->getProfile($userId);
$this->view->load('userProfile', $profileData);
}
// domain.com/user/friends/page-14
function friends()
{
//GET data from a Model
$friendsData = $this->model->getFriends();
$this->view->load('userFriends', $friendsData);
}
}
For me, I developed a separate object that handles all template display methods. This is good because you can then ensure that all the resources you need to display your UI is contained in one object. It looks like you've isolated this in Core_View.
Then, when an AJAX call is made, simply detect that it is an AJAX call. This can be done by either making the AJAX call through an AJAX object, which then references other objects, or you can take an easy approach and simply set an extra POST or GET field which indicates an AJAX call.
Once you've detected if it's an AJAX call, define a constant in your MVC such as AJAX_REQUEST. Then, in your template/UI object, you can specify that if it's an AJAX call, only output your response text. If it isn't, proceed with including your template files.
For me, I send it through an AJAX object. That way I don't have to worry about making a single output work for both cases. When it's ready to send a response, I just do something to the manner of print( json_encode( ...[Response]... ) ).
well, it would all start with normal request which would load the initial page. there are many options as to handle this but let's say that you start with /users/friends page which would list all your friends. then each of the friends should have link to specific friend's profile -- now this is the moment where ajax could kick in and you could ajaxify links to your friend profiles - this means that instead of normal you would instead use let's say jQuery and setup click handler in a such way that
$("a").click(function(){$.post($(this).attr("href"), null, function(data){$("#content").html(data);}});
this would use "href", and upon click would make post request to your backend. at backend, if you see that it's post, then you would just return the content for that particular friend. alternatively, if you have get request, you return all - header - content - footer.
if you use technique above, make sure to properly handle the data you receive. e.g. if there are further actions that should be done via ajax, make sure to "ajaxify" the data you get back. e.g. after updating html of the content, again apply the $("a").click routine.
this is just trivial example, to kick you off, but there are many more sophisticated ways of doing that. if you have time, I suggest reading some of agiletoolkit.org, it has nice mvc + ajax support.
You will need to use a different view. Maybe something like:
funciton friends() {
$this->view = new Ajax_Request_View();
$friendsData = $this->model->getFriends();
$this->view->load($friendsData);
}
Here is the code using CodeIgniter:
The problem I encounter:
The controller will have some functions call view, and it
separated, but it is still very close with the logic itself, if the
controller change to return in JSON or XML to display result, it seems
very trouble.
Seems many method, but each one is depends another.
I think it is difficult to track the code.
Please give some suggestions thank you.
*Please reminded that, it is only the controller class. the load view is actually prepare the data for the view, won't render the page. also the doXXX function call model is only use the model method, it won't have any SQL statement. The MVC is separated, but the controller also have the functions related to the view or model, make it quite messy.
class User extends CI_Controller
{
public function register()
{
//check is logged in or not
//if not logged in , show the register page
}
public function show_register_page()
{
//generate the UI needed data , and call the view to render, and will the user will post back a valid_register function
}
public function valid_register()
{
//do all the valid logic, if success,
//do the do_register
//if fail, valid_register_fail
}
public function valid_register_fail()
{
//check is logged in or not
//show the valid register fail page
}
public function show_valid_register_fail_page()
{
//generate the UI needed data , and call the view to render
}
public function do_register()
{
//insert data in the db, the Model will be called
//if something go wrong in db, show the error page
//if everything is success, show the register success
}
public function show_db_error_page()
{
//generate the UI needed data , and call the view to render
}
public function show_register_success()
{
//generate the UI needed data , and call the view to render
}
}
1. The controller will have some functions call view, and it
separated, but it is still very close with the logic itself, if the
controller change to return in JSON or XML to display result, it seems
very trouble.
Depends on how you organized your code and what you actually pass into the view (template). If that's well structured, you can have one view for HTML, one for XML and one for json, where-as json normally just encodes the view variable's (see json_encodeDocs).
2. Seems many method, but each one is depends another.
Well, just don't do it :) The names look like you wanted to "code that into". Keep it apart. Make those function actually actions that a user performs:
register - that action handles the registration process
Make a login controller out of it that handles anything you need:
login - the login action
lost_password - the lost password action
register - the registration action
activate - the registration activation action
Everything else does not belong in there. There is no need for an action to display some page - the controller itself can decide which view to pick.
Next to that you don't need to display database errors. CI takes care of that. Just put only in what's needed and keep things simple. That should help you to reduce the number of methods and the code therein as well.
3. I think it is difficult to track the code.
Sure. Too many functions with not really speaking names. Keep things simple. It's not easy, but give naming and reducing the overall logic some love.
I have a page /discussion and I want to implement pagination in it. Now, I want that for the first time the page should load as /discussion, which means that this act as if it was /discussion/page/1. For the other page the url will be /discussion/page/$pagenumber.
Now, the problem is index(). Normally, I initialize all the page data in the index() and then load the view with the initialized data. But, here I’ll have to initialize default page stuff in index() and then the pagination stuff in page(). So, is there a way of sending another set of data from page() to the view? I don’t want to load the view since it will be loaded by the index().
However, I think it is not possible to do what I mentioned above. So, maybe I should keep my index() empty and do all the initialization in the page() and then load the view there. What do you say?
You don't need both the "page" and "index" methods, just use a route.
Using an index() method and dropping the page() method:
$route['discussion/page/(:num)'] = 'discussion/index/$1';
/discussion still gives you page 1, requesting discussion/page/32 will map to discussion/index/32
This assumes you're grabbing the page number as an argument (url segment), like so:
function index ($page = 1) {}
If you are doing something else, a route is still appropriate, maybe just not the one provided.
I suggest to have a look at PEAR's awesome Pager package. It automatically generates a pager and gives you the correct indexes depending on the (GET) input variables.
It sounds like you're trying to have your page method decorate your index method. Without knowing more about the overall structure of the controller, there really isn't terribly much to say, but it sounds like the below will help:
function page( $pos )
{
$this->index( $pos );
}
// a default parameter lets you ensure that this does not neet to have a page set.
function index( $pos = 0 )
{
// when calling the DB (I'm guessing that is where the pagination really happens)
// COUNT should be defined in the config if possible.
$this->db->where/*... add more here...*/->limit( COUNT, $pos );
}
Realistically, you should look into your URI routing class or using the _resolve method, but this should do what you need it to.
I'm not quite sure what your problem is.
If you have a index() method you can set all the pagination information there, remember you have to tell the pagination library which uri segment will be using to get the page number, and that doesn't have anything to do with the index().
There is no page() method in the controller, all of the pages are the same index() with a different set of paginated data, given by the uri_segment defined as the page number, that means all the stuff that is not related to the paginated queryset are intact through the pages.
I have a CI page that will load to a div in view file, using jQuery. Using switch(page_parameter), I control what is showing from the page.
When I call the page for 3rd time, I set a value to the class array.
But when I call the 4th time, the array become empty.
I was wondering, is it actually possible to use the class property to store value that can be used after page re-access? Or something missing in my head?
I know that using session is not a good idea, since the real array is a big chunk of serialized xml.
Here's my code:
class MyClass extends MY_Controller
{
public static $pitems = array();
function Hotel(){
parent::MY_Controller();
}
function new_campaign(){
$params = $this->uri->uri_to_assoc();
switch($params['step']){
case '3' : self::$pitems = array("test","another"); //here the class array was set successfully
$this->load->view('viewer');
break;
case '4' : print_r(self::$pitems); //here the array is empty
break;
}
}
In the viewer page, there's a call to the page:
Next page
Same issue also with $this->
What am i missing here?
Thanks in advance~
edit:
I saw a script that has similar scenario. it successfully reused the variable set in the constructor, instead of treating it as a class variable. i'll look thorough to confirm this, but for now, i'll close this thread. Thanks Chris for sharing.
Im not really sure what your trying to do but I have users jQuery post()/get()/ajax() many of times in CI and have had no problems. So despite not knowing or understanding what your trying to do. I thought I'd at least say I know loading data without refresh in CI through something like jQuery isn't an issue. Example on system I built on CI had a twitter like feed of tweets where jQuery on a timer was polling for new data and coming back with it each time accordingly if something new was to be shown.