Welcome Guest, Not a member yet? Register   Sign In
Post your controller!
#11

[eluser]überfuzz[/eluser]
[quote author="narendran" date="1251728394"]hi,
I'm doing Cart system like products,category,order etc.for this i have to write code for
admin area to edit,delete,add,giving authorization to customers to login or not.


frnds, I'm Beginner of CI.so help me how to do this by CI.give me reference sites.sample codes also.
hope i will get a Good response from u.

thanks,

Narendran[/quote]
Double posts tend to annoy users of this forum.
#12

[eluser]Dam1an[/eluser]
[quote author="überfuzz" date="1251733381"][quote author="narendran" date="1251728394"]...[/quote]
Double posts tend to annoy users of this forum.[/quote]

And triple posts even more so
And don't even get me started on the fact you're just piggy backing off oter peoples threads!
#13

[eluser]jegbagus[/eluser]
hey bro, your code look really mess...
better not to use a mvc framework if you won't separate the code in mvc way..

[quote author="James Brauman" date="1251631147"]Lets see what everyone elses coding standards look like, how they comment, and how they structure thier controllers. Perhaps we can learn something. Obviously, remove any sensitive information :-) Note: If your controller is absolutely massive, maybe post a different one.

Code.php
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Code extends Controller
{
    function __construct()
    {
        parent::Controller();
    }
    
    function index($code_name)
    {
        $this->load->model('code_model');
        $this->load->library('tank_auth');
        $this->load->library('form_validation');
        
        // If the code url is not valid, show error message.
        $sql = 'SELECT * FROM codes WHERE url_name = ?';
        $bindings = array($code_name);
        $listing = $this->db->query($sql, $bindings)->row_array();
        if (empty($listing))
        {
            // Show error
            return;
        }
        
        // If we have feedback, lets post it.
        if ($this->tank_auth->is_logged_in() && $this->input->post('feedback'))
        {
            $this->form_validation->set_rules('feedback', 'Feedback', 'trim|required|xss_clean');
            if ($this->form_validation->run())
            {
                // Insert the data into the feedback table
                $sql = 'INSERT INTO feedback(code_id, user_id, feedback) VALUES (?, ?, ?)';
                $bindings = array ($listing['id'], $this->tank_auth->get_user_id(), set_value('feedback'));
                $this->db->query($sql, $bindings);
            }
        }
        
        // If we have a rating, lets rate it.
        if ($rating = $this->input->post('rating'))
        {
            if (is_numeric($rating) && $rating >= 1 && $rating <= 5)
            {
                // Get the number of votes that this IP address has on this code.
                $sql = 'SELECT * FROM ratings WHERE INET_NTOA(ip) = ? AND code_id = ?';
                $bindings = array ($_SERVER['REMOTE_ADDR'], $listing['id']);
                $query = $this->db->query($sql, $bindings);
                
                // We should only let them vote if they haven't already voted.
                if ($query->num_rows() == 0)
                {
                    $sql = 'INSERT INTO ratings (code_id, ip, rating) VALUES (?, ?, ?)';
                    $bindings = array ($listing['id'], $_SERVER['REMOTE_ADDR'], $rating);
                    $this->db->query($sql, $bindings);
                }
            }
        }
        
        // Add one to the number of views that this code has.
        $sql = "UPDATE codes SET views = views + 1 WHERE id = {$listing['id']}";
        $this->db->query($sql);
    
        // Retrieve language, category, tag and user arrays and add them to the listing.
        $sql = "SELECT * FROM languages WHERE id = {$listing['language_id']}";
        $listing['language'] = $this->db->query($sql)->row_array();
        unset($listing['language_id']);
        
        $sql = "SELECT * FROM categories WHERE id = {$listing['category_id']}";
        $listing['category'] = $this->db->query($sql)->row_array();
        unset($listing['language_id']);        

        $sql = "SELECT username FROM users WHERE id = {$listing['user_id']}";
        $listing['user'] = $this->db->query($sql)->row_array();
        unset($listing['user_id']);
        
        // Retrieve rating average and rating number and add it to listing
        $sql = "SELECT COUNT(rating) as rating_count, SUM(rating) / COUNT(rating) as average FROM ratings WHERE code_id = {$listing['id']}";
        $listing['rating'] = $this->db->query($sql)->row_array();
        
        // Retrieve the tags that this listing has
        $listing['tags'] = $this->code_model->get_tags($listing['id']);
        
        //echo '<pre>', print_r($listing, true), '</pre>';
        //return;
        
        // Render the partial view.
        $partial_data = array ('listing' => $listing);
        
        // If the user is logged in, lets add it to the partial data
        if ($this->tank_auth->is_logged_in())
        {
            $sql = 'SELECT * FROM users WHERE id = ?';
            $bindings = array($this->tank_auth->get_user_id());
            $partial_data['user'] = $this->db->query($sql, $bindings)->row_array();
        }
        
        // Get a list of feedback and add it to the partial data
        $sql = "SELECT feedback.*, users.username
                FROM feedback
                INNER JOIN users
                ON feedback.user_id = users.id
                WHERE feedback.code_id = {$listing['id']}
                ORDER BY feedback.time_posted ASC";
        $partial_data['feedback'] = $this->db->query($sql)->result_array();
        
        $partial_rendered = $this->load->view('pages/partial/code/index', $partial_data, TRUE);
        
        // Render the layout
        $layout_data = array(
            'content' => $partial_rendered
        );
        $this->load->view('pages/layout', $layout_data);
    }
    
    function _remap($code_name)
    {
        $this->index($code_name);
    }
}
[/quote]
#14

[eluser]brianw1975[/eluser]
Here's a controller that I wrote up when I was first learning CI... adding it because it's an example of using _remap and it has pagination.

(please don't make fun of the smarty usage -- I do it this way because I can tell users if they want to make/change templates they can read the smarty handbook instead of learning PHP)

and yes!!! no documentation! lol... I'm the sole programmer(owner actually, so consider this code now under CC license, fwiw) and this controller has very specific usage.

Code:
&lt;?
class Users extends Controller {

    function Users()
    {
        parent::Controller();
        $this->load->model("users_model",'users');
        $this->config->set_item('per_page',36);
    }
    
    function _remap($name = '')
    {
        switch($name){
            case "index":
                global $APPCFG;
        
                $this->mysmarty->assign_by_ref("CFG",$APPCFG);
                $this->mysmarty->assign("base_url",$this->config->item('base_url'));
                $this->mysmarty->assign("page_name","Users");
                $this->mysmarty->assign("page_keywords","");
                
                $users = $this->users->getAll();
                
                $config['base_url'] = $this->config->item('base_url').'/users/page/';
                $config['total_rows'] = $users->num_rows();
                
                $this->pagination->initialize($config);
                $this->mysmarty->assign("links",$this->pagination->create_links());
                
                $this->mysmarty->assign_by_ref("users",$this->users->getAll(true,$this->config->item('per_page')));
                $content = $this->mysmarty->fetch("users_table.php");
                
                $this->mysmarty->assign("content",$content);
                $this->mysmarty->display("home.php");
            break;
            case "page":
                global $APPCFG;
                $config['per_page'] =36;
                
                $this->mysmarty->assign_by_ref("CFG",$APPCFG);
                $this->mysmarty->assign("base_url",$this->config->item('base_url'));
                $this->mysmarty->assign("page_name","Users");
                $this->mysmarty->assign("page_keywords","");
                $original_query = $this->users->getAll();
                
                $users = $this->users->getPage($this->uri->segment(3, 0),$this->config->item('per_page'));
                
                $config['base_url'] = $this->config->item('base_url').'/users/page/';
                $config['total_rows'] = $original_query->num_rows();
                
                $this->pagination->initialize($config);
                
                $this->mysmarty->assign("links",$this->pagination->create_links());
                
                $this->mysmarty->assign_by_ref("users",$users->result_array());
                $content = $this->mysmarty->fetch("users_table.php");
                
                $this->mysmarty->assign("cols",4);
                $this->mysmarty->assign("content",$content);
                $this->mysmarty->display("home.php");
            break;
            default:
                $this->_showUsers($name);
            break;
        }
    }
    function _showUsers($name)
    {
        global $APPCFG;
        
        
        $this->mysmarty->assign("page_name","User: $name");
        $this->mysmarty->assign("page_keywords","$name, stories, websites");
        
        $users= $this->users->getOne(0,$name);
        
        $this->mysmarty->assign("content",$users);
        $this->mysmarty->assign("inc_file","blocks/archive_bio.php");
        $this->mysmarty->assign("title", "User Details");
        
        $this->mysmarty->assign("content",
            $this->mysmarty->fetch("blocks/common/content.php"));
            
        $this->mysmarty->display("home.php");
    }
}
?&gt;

I know that I used _remap for pretty link and SEO niceties, but looking back on it, I'm not exactly sure _why_ i chose to do it that way.... but like i said, it's a sample of using remap and pagination.

FYI
/site.com/users/ gives a list of users
/site.com/users/page/2 shows page two of the users
/site/com/users/(user_name) shows the information for that particular username

Ok, lemme have it.
#15

[eluser]n0xie[/eluser]
[quote author="brianw1975" date="1251880247"]

Ok, lemme have it.[/quote]

If you insist...

Code:
public function index() {}
public function page() {}
private function show_user($username) {}

    public function _remap($name = NULL)
    {
        if (method_exists($this,$name))
        {
            $this->{$name}();
        }
        else
        {
            $this->show_user($name);
        }
    }
#16

[eluser]GSV Sleeper Service[/eluser]
Code:
class everything extends MY_Controller {
    
    public function __construct()
    {
        parent::__construct()
    }
    
    public function index()
    {
        $this->load->model('everything_ever');
        $data = $this->everything_ever->do_whatever_it_is_i_want_to_do();
        $this-load->view('omniview',$data);
    }
    
}
#17

[eluser]brianw1975[/eluser]
Thanks for the suggestion, however, one minor drawback and one big drawback for me:

minor) It doesn't make the code functionally better, just prettier.
big) It's not PHP4 compatible

But thanks though.


[quote author="n0xie" date="1251898932"][quote author="brianw1975" date="1251880247"]

Ok, lemme have it.[/quote]

If you insist...

Code:
public function index() {}
public function page() {}
private function show_user($username) {}

    public function _remap($name = NULL)
    {
        if (method_exists($this,$name))
        {
            $this->{$name}();
        }
        else
        {
            $this->show_user($name);
        }
    }
[/quote]
#18

[eluser]n0xie[/eluser]
I beg to differ. Aside from being not PHP4 compatible (which I agree could be a drawback but since I only do PHP5, it never crossed my mind), it is a much cleaner and all around better solution. There are a ton of reasons (easier to add new pages, encapsulation, every function has it's own scope) but I'll just leave you with this: this way you stick to the normal CI conventions by which you adhere to the principle of least surprise.
#19

[eluser]Jay Logan[/eluser]
Here is a function that is part of one of my internet portals that let's me check the position a web site is in Google results.

Code:
function find_google_position()
    {
        $this->load->helper(array('dom', 'date'));
        $this->load->library(array('form_validation', 'typography'));
        
        $this->form_validation->set_rules('url', 'URL', 'trim|required|prep_url');
        $this->form_validation->set_rules('keywords', 'Keywords', 'trim|required');

        if ($this->form_validation->run() == FALSE) {

            redirect('admin/tools/google_positions');

        } else {

            $keywords = str_replace(' ', '+', $this->input->post('keywords'));

            $html = file_get_html('http://www.google.com/search?q='.$keywords.'&num=100&start=0');
            $new_lines = array("\t","\n","\r");
            $content = str_replace($new_lines, "", html_entity_decode($html));
    
            $results_array = $html->find('h3.r');
            
            foreach ($results_array as $result) {
            
                if (substr($result->find('a', 0)->href, -1) == "/") {
                
                    $clean_results_array[] = substr($result->find('a', 0)->href, 0, -1);
                
                } else {
            
                    $clean_results_array[] = $result->find('a', 0)->href;
                    
                }
    
            }
            
            foreach ($clean_results_array as $key => $value) {
            
                if ($value == $this->input->post('url')) {
                
                    $position = $key + 1;
                
                }
            
            }
    
            $google_position_info['url'] = $this->input->post('url');
            $google_position_info['keywords'] = $this->input->post('keywords');
            
            if (isset($position)) {
            
                $google_position_info['current_position'] = $position;
                
            } else {
            
                $google_position_info['current_position'] = "Not within top 100.";
            
            }
                
            $google_position_info['date_added'] = time();
            
            $this->tools_model->add_google_position($google_position_info);
            redirect('admin/tools/google_positions');
            //print_r($clean_results_array);
        }

    
    }
#20

[eluser]Nick Husher[/eluser]
This is the main "directory" controller for a classifieds project I'm working on in my spare time. Public_Page extends Template_Controller which in turn extends Controller. Template_Controller defines standard methods for constructing pages, so calls to $this->display are automatically inserted into a generic page-level template (changable with a call to $this->set_template). The template for the body of the page is automatically derived from the controller method that was called (captured by PHP's debug_backtrace function, which is probably a misuse of the function, but whatever), so a call to Main->_listing uses the /views/pages/main/_listing.php as its body view.

The template controller also defines an error function (for reasons that are obvious in a second) that allows me to display site-wide errors within the current site design. There are other ways to do it, but this seemed the most appropriate. I'm still working on an automated exception catcher to throw up styled 500 errors when something internal goes wrong.

The routes.php file remaps any non-special path (the path to the admin and user sections, as well as the special shorturl path) to /get/, so a call to http://example.com/housing/for-rent becomes /index.php/main/get/housing/for-rent. It loops through the segments to figure out what category or listing you're looking at and calls $this->_category or $this->_listing as appropriate. The algorithm is really inefficient; it should really be starting at the last segment and working forward, but for internal reasons that's quite a bit more complex and I haven't bothered to refactor it.

I can post the Template_Controller class, but it's a bit of a dog's breakfast. I need to break out repeated functionality into separate functions and improve its configurability before I'd call it "good" code.

Code:
class Main extends Public_Page {
    function Main() {
        parent::Public_Page();
        
        $this->load->model('category_model');
        $this->load->model('listing_model');
    }
    function index() {
        
        $cats = $this->category_model->get_category_tree();
        
        $data = array(
            'categories' => $cats
        );
        
        $this->display('Front Page', $data);
    }
    
    function get() {
        $segments = $this->uri->segment_array();

        $category = $this->category_model->get_category_by_name($segments[1]);

        if(!$category) {
            $this->error(404, "Could&rsquo;t find category " . $segments[1]);
            return;
        }

        for($i = 2, $l = count($segments) + 1; $i < $l; $i++) {
            $segment = $segments[$i];
            $children = $category->getNode()->getChildren();
            $matching_child = null;

            if(is_numeric($segment)) {
                $this->_listing($this->listing_model->get_listing_by_id($segment));
                return;
            } else {
                foreach($children as $child) {
                    if($child->url_name == $segment) {
                        $matching_child = $child;
                        break;
                    }
                }
                if(!$matching_child) {
                    $this->error(404, "Couldn&rsquot;t find category " + $segment);
                    return;
                }
                $category = $matching_child;                
            }
        }
        
        $this->_category($category);
    }
        
    function _listing($listing) {
        $this->display($listing->title, array('listing'=>$listing));
    }
    
    function _category($category) {
        $lst = $this->listing_model->get_listings_in_category($category);
        $this->display($category->name, array('category'=>$category, 'listings'=>$lst));
    }
}

EDIT: Also, I'm using Doctrine PHP as an ORM using my Drop-in PHP Doctrine plugin, that's what all the getChildren() and getNode() business is about.




Theme © iAndrew 2016 - Forum software by © MyBB