Jump to content

Recommended Posts

hey guy I've just recently re-altered my autoloader class which works with namespaces but it also calls classes which aren't namespaced, like so:

$class = new myclass();

instead of

$class = new Class\Myclass;

im wondering have i defeated the whole point of namespacing and if all my classes should actually be namespaced :suicide:

 

hope its not such a pointless question :sweat:

Link to comment
https://forums.phpfreaks.com/topic/290402-autoloading-namespace/
Share on other sites

But what I'm confused at is...I've started to adapt my framework classes to being namespaced but I'd also have to add namespaces to my customer controllers:/...should my controllers and models be called without being namespaced?...so should all classes be namespaced in reality...thank you

If you use namespaces then everything (well, almost everything) should be namespaced. Personally I keep utility-type functions not namespaced, but only functions.

 

Controller classes could be under Framework\Controllers, models under Framework\Models, etc.

Edited by requinix

One of the benefits of namespaces is that they prevent collisions. For example, you can use a code library that has a class named 'User' and you could also have a class named 'User' in your code base.

 

Also, I find that it's a nice way to organize your code and see if you know what you're doing. For example, if a namespace has 100 classes, it's a good sign that you probably need to do some refactoring. 

 

And, it helps you see where the class that you use is coming from. An external library? Your own code? If so, where? Is it normal that you import a view class from a model class? etc... 

 

That being said, use namespaces all.. the... time... ;)

thanks you guys...just a few more things I wanna ask if you don't mind me picking you brains

 

if I namespace a class and call a call inside that class' method like so

$class = new hello;

it comes back with a error:

 

cannot find class my\namespace\hello;

 

is that because its only looking in the my\namespace directory and I would need to call the hello class (eg. utilities\hello) by its actually namespace?...but what happens if the class hello doesn't have a namespace?...is it impossible to load it?

PHP will look in the current namespace for the class. If you need it from somewhere else then either (a) use

use utilities\hello; // (no leading backslash because it is always absolute)
$class = new hello;

// or
use utilities\hello as helloUtility;
$class = new helloUtility;
or (b) use the fully-qualified name

$class = new \utilities\hello; // (leading backslash because it is otherwise relative)
Edited by requinix

how my customer model looks:

namespace Libray\Models;

use MVC\Model\Model as Model;

class Index_Model extends Model
{
	
}

autoloader:

use Exception\Autoloader as Exception_Handler;

class Autoloader
{	
	protected $_class_prefix       = '';
	protected $_class_paths        = array();
	protected $_ignore_directories = array('.', '..', '.settings');
	
	public function __construct()
	{
		spl_autoload_register(array($this, 'load_class'));
		$this->get_class_paths();
	}
	
	protected function is_collision($file)
	{
		$paths   = $this->_class_paths;
		$file    = $file . '.class.php';
		$matches = 0;
		
		foreach ($paths as $class_path => $file_name)
		{
			if (substr($class_path, -strlen($file)) === $file)
			{	
				$matches++; 
				
				if ($matches > 1)
				{
					return true;
					break;
				}
			}
		}
		
		return false;
	}
	
	protected function load_class($file)
	{	
	    $file  = strtolower($file);
	    $paths = $this->_class_paths;
	       
		try
		{	
			if (preg_match('/\\\\/', $file))
			{
				$file = str_replace('\\', DS, $file) . '.class.php';
				                                 
				foreach ($paths as $class_path => $file_name)
				{	
					if (substr($class_path, -strlen($file)) == $file)
					{
						require_once $class_path;
						break;
					}
				}
			}
			else 
			{
				$path = array_search($file, $paths);

				if (!$this->is_collision($file))
				{
					if (!class_exists($file, false) &&
					    file_exists($path))
					{
						require_once $path;
					}	
					else
					{
						throw new Exception_Handler(sprintf("Class '%s' not found.<br />\n", $file));
					}
				}
				else 
				{
					throw new Exception_Handler(sprintf("Unable to load '%s' due to name collision.<br />\n", $file));
				}
			}
		}
		catch (Exception_Handler $e)
		{
			echo $e->getMessage();	
		}
	}	
		
	protected function get_class_paths($path = PARENT_DIRECTORY_PATH)
	{
		$ignore_directories = $this->_ignore_directories;
	
    	$dh = opendir($path);

    	if ($dh)
    	{
		    while (false !== ($file = readdir($dh)))
			{   
				if (!in_array($file, $ignore_directories))
				{
					if (is_dir($path . DS . $file))
			        {
			      		$this->get_class_paths($path . DS . $file);
			        }
			        else if (preg_match('/\.class\.php$/i', $file))
			        {
			        	$entry = $path . DS . $file;
			        	$file  = substr($file, 0, -10);
			        	
			           	$this->_class_paths[$entry] = $file;
			        }
				}
			}
			
			closedir($dh);
    	}
    }   
}

autoloader works sweet altough i still have a few alterrations to make like cache and prefix...hope im on the right track...thanks guys

Edited by Destramic
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.