codeigniter - routing a non existent URI - php

So in this codeigniter installation, I have a controller called user. In its index() I accept a user_name and show that user's profile.
class User extends CI_Controller
{
function index($user_name)
{
//show user profile...
}
}
This works fine. However to view a profile the visitor has to go to: <site>/user/john_doe
I want the URL to be <site>/john_doe. I know this is not possible using the default controller/function/arg setup that codeigniter has. Can I map this in routessuch that if a visitor types <site>/john_doe, the system recognizes there is no controller called john_doe it internally renders <site>/user/john_doe (however it should keep the original short url)
Also, there will be a side effect concern of what if a user creates a username called user which is already a valid controller...but I guess that is a secondary concern (can block all controller names as keywords so user cannot register one of them)

You can, by putting the following rule at the bottom of your routing file.
$route['/(:any)'] = "/user/index/$1";
It is of absolute importance that this rule be placed at the bottom. If you put it on top, all the URL's you enter will match the user/index controller.

Related

how display checked filter variable value in url codeigniter

I am a basic user of code igniter and PHP.I have some products page with filters. How to created a URL link like this:
http://somepage.pl/products?color=red
I know I can do above url when I will change the config line:
$config['enable_query_strings'] = FALSE; on TRUE.
But I want to use this option only one controller and one function.
Your best bet is to rely on codeigniter's native URI rewriting.
By default, (I'm not getting into custom routes here, but you might if you understand them) URLs served by Codeigniter will look like this:
BASE URL/Controller/method/params
Base url will be what you define in the config and more often than not, it'll be the base domain of your site, like example.com.
Since CI is built based on MVC architecture, all your functionality must "live" on different methods within one or many controllers. So, for example, you might have a controller named products and within that controller you may have a method (for simplicity's sake: function) called lookupProductById that will take one parameter ($product_id). It'll look like this:
class Products extends CI_Controller {
public function lookupProductById($product_id = null)
{
// whatever you need to do (like querying the database to fetch info for the product with a certain product ID) goes here
// for instance, start by checking that the product ID was passed in the URI
if ($product_id == null)
{
// handle exception
}
else
{
// query the database and fetch info for the product whose ID is $product_id
}
}
}
so, when accessing example.com/products/lookupProductById/8 you'll be able to fetch the info related to product ID 8
You may want to read the CI documentation (the introductory chapters and tutorials will guide you through a (very) basic understanding of how MVC frameworks operate, how controllers, models and views interact to produce a result, etc.) to better understand what you're getting into :)

Suggestions for website template/design - Backend

I'm creating a website using Codeigniter which hosts online novels/e-books. The novel(s) have multiple chapters similar to a hard copy. Im planning to design the layout as following.
User goes to chapter 1, so the URL would be site.com/novel/chapter1/pageno
I plan to create a novel controller which has chapter1,2.. etc as its functions. The chapter function receives an input and gets the same form either a database or from a text file. I'd also want to store user progress which can be resumed later. I plan to use the chapter/pageno as the reference for where the user currently has stopped.
I'd like to know if this approach is good and is it possible to limit the functions and make it more generic. Alternative approach to this concept would also be helpful.
yes you can make it more generic it routes you have to add route in routes.php under config directory like this
$route['novel/(chapter-[0-9]+)/(:any)'] = 'novel/chapter/$1/$2';
now url will be www.site.com/novel/chaper-20/60
novel controller
class Novel extends CI_Controller{
function chapter($chaper_no,$page_no){
echo $chpter_no,' ',$page_no;
}
// if you don't want to pass variables to chapter function use the following
function chapter(){
$chapter_no = $this->uri->segment(2);
$page_no = $this->uri->segment(3);
}
}
if you are registering users in you site create a bookmark link ask him to save the page, if you are not registering users on your site you can set cookie to save user progress by just clicking same bookmark link or make it on each page load

Using the same model across various controllers CakePHP

I've just started reading up on CakePHP and everything is going pretty good so far, though I have a query on the best way to do the following:
I have a "User" model and a "UsersController" controller.
I currently have a "home" page which is controlled by the home_controller.php (obviously). The home page contains a registration for for a user.
The Question
When the form is posted from the home page, I need to access the User model (from the home controller).
What is the best practice for this task?
If I understand the situation correctly, I would post the form to some function in users controller. Then this function would save the data, or log in, or whatever. Finally make redirect back to home for example.
you can easily share one model across many controllers
var $uses = array('ModelName');
I do that with User Model and
Account Controller (Login, Register, ...)
Members Controller (Search, Listing, Profile, ...)
Overview Controller (Start Page, Home, ...)
for example. they all share the User Model.
I currently have a "home" page which is controlled by the home_controller.php (obviously) What other methods do you have in home_controller, other than index? And in Cake convention, the controller is plural, so: users, categories... Most likely, you are not aware of pages_controller and routing in Cake.
Anyway, yes, you can make a post to any controller (or even to another domain) from any page, just like any regular HTML page. echo $this->Form->create('User', array('controller'=>'users','action' => 'register')); You can read more here: http://book.cakephp.org/view/1384/Creating-Forms

How can I switch between views from one action in a controller

I'm building a job site where you have two types of users who sign in i.e job seekers and prospective employers. Now both create their accounts from different sign up pages however they sign in from the same login form and are redirected to their account pages. The thing is that the base account page for each should be different5 obviously however I need it to point under the exact same url i.e www.mysite.com/my-account
What would be the best way to do it, is it possible to choose from within a controllers action what view to use here?
You can render a different view inside the controller with $this->render('path/to/view.phtml');
A cool way could be in the init of your controller you set a different base path for the view according to the type of account $this->view->setBasePath('/path/to/account/type/'); So you don't need to call $this->render(); but the render directly will look into the right folder, if you have one folder per account type

Data from multiple models in one view (web page)

I'm new to the MVC pattern but have been trying to grasp it, for example by reading the documentation for the CakePHP framework that I want to try out. However, now I have stumbled upon a scenario that I'm not really sure how to handle.
The web site I'm working on consists of nine fixed pages, that is, there will never exist any other page than those. Each page contains something specific, like the Guest book page holds guest book notes. However, in addition, every page holds a small news box and a short fact box that an admin should be able to edit. From my point of view, those should be considered as models, e.g. NewsPost and ShortFact with belonging controls NewsPostController and ShortFactController. Notice that they are completely unrelated to each other.
Now, my question is, how do I create a single view (web page) containing the guest book notes as well as the news post box and the short fact? Do I:
Set up a unique controller GuestBookController (with an index() action) for the guest book, so that visiting www.domain.com/guest_book lets the index action fetch the latest news post and a random short fact?
Put static pages in /pages/ and in let the PagesController do the fetching?
< Please fill in the proper way here. >
Thanks in advance!
It sounds like you need to look into elements, or else you may be able to embed this into the layout - but its neater to use an element if you ask me, keep the things separate.
http://book.cakephp.org/2.0/en/views.html#elements
These allow you to have create small views that you are able to embed into other views.
You may also need to put some logic into the AppController (remember all other controllers extend the app controller) to load the data required for these views. The beforeRender function should be useful for this - its one of the hook functions cakephp provides, so if you define it on a controller, its always called after the action is finished before the view is rendered.
Something like this in your AppController should help:
function beforeRender() {
$this->dostuff();
}
function doStuff() {
// do what you need to do here - eg: load some data.
$shortfacts = $this->ShortFact->findAll();
$news = $this->NewsPost->findAll();
// news and shortfacts will be available within the $shortfacts and $news variables in the view.
$this->set('shortfacts', $shortfacts);
$this->set('news', $news);
}
If there are models you need in the app controller for use within this doStuff method, then you need to define them within uses at the top of the AppController
class AppController {
var $uses = array('NewsPost', 'ShortFact');
}

Categories