March 24, 2012

Codeigniter controller and model with same name collison

Question by musa

I’m try something from this comment idea Code Igniter Controller/Model name conflicts

find class name variable on core/CodeIgniter.php :

$class = $RTR->fetch_class(); and change like that:
$class = 'Controller' . $RTR->fetch_class();

now change controller name:

class ControllerUser extends CI_Controller { ...

It works, now I can use User model and User controller. But my question is, Does it make sense? or Does the problem? (sorry my bad English)

Answer by Starx

To get around this issue, normally most people add the ‘_model’ suffix to the Model class names

I think it is better to add a suffix to the Controllers instead, since they are almost never referenced by their class names in your code.

First we need to extend the Router class.

Create this file: “application/libraries/MY_Router.php”

class MY_Router extends CI_Router {
    var $suffix = '_controller';

    function __construct() {
        parent::CI_Router();
    }

    function set_class($class) {
        $this->class = $class . $this->suffix;
    }

    function controller_name() {

        if (strstr($this->class, $this->suffix)) {
            return str_replace($this->suffix, '', $this->class);
        }
        else {
            return $this->class;
        }

    }
}

Now edit “system/codeigniter/CodeIgniter.php”

line 153:

if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT))  

line 158:

include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT);  

Next, edit: “system/libraries/Profiler.php”, line 323:

$output .= " 
<div style="color:#995300;font-weight:normal;padding:4px 0 4px 0">".$this->CI->router->controller_name()."/".$this->CI->router->fetch_method()."</div>";  

Source

March 1, 2012

php data classes?

Question by mazzzzz

I’ve learned most of my OOP practices from C#, and coded php primarily in MVC but without custom objects for data types (user information and such I primarily stored in associative arrays). I’m wanting to take what I’ve learned in C# (making structs, or data classes basically, to store specific types of data, such as a user record, or say an article’s information) into php. This is so I can know exactly what data values to expect (because they’re defined fields, instead of just added to an array), allowing a bit more abstraction between controller and view.

Is there a certain way to do this in php, and in the MVC design pattern specifically? I am curious where I should put the definitions of these new “data types.”
Or am I just thinking about this in the wrong way, and there is a better way to do it?

EDIT:
A C# example of what I’m trying to accomplish:

class program1
{
    public void main ()
    {
        Article randomArticle = getArticle (); //instead of returning an object array, it returns a defined data type with predefined fields, so I don't need to guess what's there and what isn't
        Console.WriteLine(randomArticle.title);
        Console.ReadLine();
    }
    public Article getArticle ()
    {
        return new Article("Sometitle", "SomeContent");
    }
}
struct Article
{
    public Title {get; private set;}
    public Content {get; private set;}

    public Article (string title, string content)
    {
        this.Title = title;
        this.Content = content;
    }
}

(idk if the above actually would compile, but it gives you the gist of what I’m attempting to do in PHP)

Answer by zvnty3

In PHP, you are free to write your own systems that accomplish MVC. Instead of rolling your own to start, though, I suggest looking into using an existing system. There’s a huge ecosphere of us php types, and a long history. By some opinions, PHP is more well-established than a younger and faster evolving C#. It’s also simpler, which is nice. Specifically, though: CakePHP is one I’d recommend. Drupal is more robust. And there’s always Zend. Advantage of going Zend is the end-to-end solution from the editor to the server optimization and security.

p.s. c# is more mvvm

EDIT: code example

class Article {

    protected $_title;
    protected $_content;

    public function setTitle( $title ) {
        $this->_title = $title;
    }
    public function setContent( $content ) {
        $this->_content = $content;
    }

    public function getTitle() {
        return $this->_title;
    }
    public function getContent() {
        return $this->_content;
    }

    /* magic not advisable; a technically valid technique, though it can lead to problems
    public function __get( $property ) {
        switch( $property ) {
            case 'title': return $this->_title; break;
            case 'content': return $this->_content; break;
            default: break;
        }
    }
    */

}

Answer by Starx

PHP is free of any logic you would like to implement. IMO, Ensuring data-types leads to a field of validations. I want you to check few terms, that will give you everything required.

  1. Type Casting/ Juggling [docs here]

    Casting is probably fastest way to stop unwanted input. The casts allowed are:

    • (int), (integer) – cast to integer
    • (bool), (boolean) – cast to boolean
    • (float), (double), (real) – cast to float
    • (string) – cast to string
    • (array) – cast to array
    • (object) – cast to object
    • (unset) – cast to NULL (PHP 5)
  2. PHP Filters

    PHP has a function filter_var (http://www.php.net/manual/en/function.filter-var.php) will helps you to compare a data type

    var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
    var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
    
  3. PHP inbuild() functions

    They are many functions in php, which can help you check the data types

    • is_array(): checks array
    • is_integer(): Check integer
    • is_object(): Check objects
    • is_float(): Checks Floating point number
    • ctype_digit(): Checks Integer

    and many more

  4. Regex Validation

    You will be able to find many resources on this on the internet.


Other Resources


Update

Your above method might turn into something like this

public function Article($title, $content) {
    if(is_string($title)) { $this -> title = $title; }
    if(is_string($content)) { $this -> content = $content; }
}
February 29, 2012

htaccess for own php mvc framework

Question by paganotti

Good Morning,
I’m building my own php framework. I would want that all request pass to index.php file except request to js css jpeg, jpg, png file. So I want that a module independently to others has own assets folder with css images and js file.

The Structure is something similar:

application
   module1
     models
     controllers
     templates
         assets
             css
             images
               test.jpg
               hello.png
             js

         view1.html.php
         view2.html.php

   module2
     models
     controllers
     templates
         assets
             css
             images
               test.jpg
               hello.png
             js

         view1.html.php
         view2.html.php
  core
    here is core file framework

  index.php

How Can I do it?

Update

My modules are under application folder. assets folder must be public.
I want a simple small url like www.example.com/module1/images/test.jpg

instead long

www.example.com/application/module1/templates/assets/images/test.jpg

Answer by Starx

Actually, the default .htaccess of zf works well for this

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
February 24, 2012

Two (almost) identical pieces of code produce separate results

Question by Marc Towler

I have been working on a little MVC project to assist in my self-learning and I have come across an issue that completely baffled me. I made a blog section in this MVC-ish system and pulled user permissions from an ACL with no problem whatsoever.
I moved onto creating a member section and as soon as i added any permissions checking I get the following error from Chrome:

No data received
Unable to load the web page because the server sent no data.
Here are some suggestions:
Reload this web page later.
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

I thought it was weird, so I double checked my error logs and nothing had shown up. So I decided to copy and paste the working blog code into the member file, reloaded and i got the EXACT same error, the only difference between the two files right now is the file name and the class name.
Here is the Blog code:

<?php
class blog extends frontController {
    public $model;
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->model = $this->autoload_model();
        $this->user  = $this->load_user();
        $this->user->getUserRoles();
    }

    public function index()
    {
        //Will only list the latest post ;)
        if(!$this->user->hasPermission('blog_access'))
        {
            $array = $this->model->list_posts();

            if(empty($array))
            {
                $this->variables(array(
                    'site_title' => 'View Blog Posts',
                    'post_title' => 'Sorry but there are no posts to display'
                ));
            } else {
                $this->variables(array(
                    'site_title' => 'View Blog Posts',
                    'list'       => $array[0],
                    'post_title' => $array[0]['entry_title'],
                    'link'       => str_replace(' ', '_',$array[0]['entry_title']),
                ));
            }
        } else {
            $this->variables(array(
                'site_title' => 'Error :: Design Develop Realize',
                'body'       => 'Sorry, but you do not have permission to access this',
            ));
        }

        $this->parse('blog/list', $this->toParse);
    }

This is the member file:

<?php

class member extends frontController {
    public $model;
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->model = $this->autoload_model();
        $this->user  = $this->load_user();
        $this->user->getUserRoles();
    }

    public function index()
    {
        //Will only list the latest post ;)
        if(!$this->user->hasPermission('blog_access'))
        {
            //$array = $this->model->list_posts();

            if(empty($array))
            {
                $this->variables(array(
                    'site_title' => 'Design Develop Realize :: View Blog Posts',
                    'post_title' => 'Sorry but there are no posts to display'
                ));
            } else {
                $this->variables(array(
                    'site_title' => 'Design Develop Realize :: View Blog Posts',
                    'list'       => $array[0],
                    'post_title' => $array[0]['entry_title'],
                    'link'       => str_replace(' ', '_',$array[0]['entry_title']),
                ));
            }
        } else {
            $this->variables(array(
                'site_title' => 'Error :: Design Develop Realize',
                'body'       => 'Sorry, but you do not have permission to access this',
            ));
        }

        $this->parse('blog/list', $this->toParse);
    }

In the member class, if I comment out $this->user = $this->load_user(); then the error disappears!!!
Just for reference here is that function:

protected function load_user()
{
    if(!$this->loader->loaded['acl'])
    {
        $this->loader->loadCore('acl');
    }

    return $this->loader->loaded['acl'];
}

Any help or suggestions would be appreciated as I am stumped!

PS yes I do have error reporting set to cover everything and no it does not log anything!

EDIT: Because all files go through index.php I have placed the error reporting there:

<?php
error_reporting(E_ALL);
ini_set('date.timezone', "Europe/London");

require_once('system/library/loader.php');

$loader = new loader();
$loader->loadCore(array('frontController', 'routing'));

EDIT 2: loadCore() is below

public function loadCore($toLoad, $params = false)
{
    //important task first, check if it is more then 1 or not
    if(is_array($toLoad))
    {
        //more then one so lets go to the task!
        foreach($toLoad as $file)
        {
            if(file_exists('system/library/' . $file . '.php'))
            {
                require_once('system/library/' . $file . '.php');

                if($params)
                {
                    $this->loaded[$file] = new $file($params);
                } else {
                    $this->loaded[$file] = new $file;
                }
            } else {
                trigger_error("Core File $file does not exist");
            }
        }
    } else {
        //Phew, less work, it is only one!
        if(file_exists('system/library/' . $toLoad . '.php'))
        {
            require_once('system/library/' . $toLoad . '.php');

            if($params)
            {
                echo(__LINE__); exit;
                $this->loaded[$toLoad] = new $toLoad($params);
            } else {
                $this->loaded[$toLoad] = new $toLoad;
            }
        }
    }
}

Update: I modified loadCore so that if it was the acl being called it would use a try…catch() and that has not helped as it will not display an error just the same chrome and IE pages

Update 2: I have spoken with my host and it seems that everytime this error occurs, apache logs the following (not sure why I cannot see it in my copy of the logs!)

[Wed Feb 22 08:07:11 2012] [error] [client 93.97.245.13] Premature end
of script headers: index.php

Answer by Starx

“Premature end of script headers” are internal server errors. Which generally occurs when script breaks and does not send any HTTP headers before send the error messages. There might be several causes to this.

  • One might be output buffering. May be the server you are using buffers the output by default. I will suggest turning off the output_buffering using output_buffering = off on php.ini [docs here].

  • Make sure you are sending correct HTTP headers also

    print “Content-type: text/htmlnn”;

There are few more suggestion on this link.
To learn more about this error, go here.

Hope it helps

January 9, 2011

Light HTML webpage designer to use along side netbeans on my mac?

Question by LondonGuy

I would like to know if there is a plugin for netbeans that would make it easy for me to edit html and build simple temp pages while coding so I can place things in the right place on my page etc..

If there isn’t a plugin is there any lightweight HTML webpage editor I could use?

Thanks in advance..

I also don’t mind buying..

Answer by Starx

Lightweight HTML Editor? :O

Try http://brandonsoft.com/htmlide/

...

Please fill the form - I will response as fast as I can!