PHP - Re-autoload Class?
I'm trying to make my own framework along the lines of CodeIgniter's basic structure. I was wondering if there's a way to automatically re-load a class?
Similar TutorialsWell PHP5 has a function __autoload() which makes it possible to load classes when needed, thereby eliminating excessive lines of include() or require(). Now I have a question about this feature, lets assume we have a class file like this: Code: [Select] interface Shop{ public function getshop(); public function displayshop(); public function purchase($name); public function sell($name); public function rent($name); } class Foodshop implements Shop{ // codes here } class Bookshop implements Shop{ // codes here } class Electronicshop implements Shop{ // codes here } class Petshop implements Shop{ // codes here } class Auction implements Shop{ // codes here, note the class name auction does not contain shop substring... } If I instantiate an object from one of these classes that implement (or extend) an interface(or an abstract class), how should I design my __autoload() function so that this class file will be loaded properly? Please help. Is using class autoload slower than including them yourself? Should I include/require the class file and use class autoload as a backup in case I had forgotten, or can I just let class autoload load all the class files and never worry about including/requiring. All classes are in the same directory and are always picked up - just want to know if it takes more time. Is it much of a difference? Are we talking 1 or 2 milliseconds per request??? Hi every one, i want to know, how do i autoload my class file in each page without using include directive. Thanks I'm beginning to study Composer and am developing a system where I separate the files core application files, as follows:
/root |-- /src |-- /App |-- /DBConfig |-- /Controller |-- /Model |-- /Core |-- /Helper |-- /Controller |-- /ModelSo, to set this setting in composer.json file and get access to all classes both /App much /Core would be this way? "autoload" : { "psr-X" : { "App\\" : "/src", "Core\\" : "/src" } }Or is there a more correct way? I have also read about PSR-0 vs PSR-4 and I am still somewhat in doubt which one to use. In my case what should I implement, PSR-0 or PSR-4? i know how to use spl_autoload_functions, spl_autoload_register, spl_autoload_unregister. but i want to know where and how to use the functions , such spl_autoload, spl_autoload_call, spl_autoload_extendsions. my understanding is spl_autoload_entendions can return the current list of extensions each separated by comma, and also i can set the extension. if i set the extension . That how it working. hello, all i am trying to learn php, and currently trying to get my head around using classes. i have the following layout: index.php Code: [Select] <?php include("config/autoloader.php"); $content = new content(); $content->get_content(); // loads Content! $content->edit_content(); // Edits Content! ?> <?php $navbars = new navbars(); $navbars->get_navbar1(); // loads navbar1! ?> config/autoloader.php Code: [Select] <?php function spl_register_autoload($content) { include_once("classes/" . $content . ".php"); } function spl_register_autoload($navbars) { include_once("classes/" . $navbars . ".php"); } ?> content.php (content class file) Code: [Select] <?php class content { public function get_content() { echo "Show me the content!"; } public function edit_content() { echo "Edit the content"; } } ?> navbars.php navbars class file Code: [Select] <?php class navbars { public function get_navbar1() { echo "Show me the navbar1!"; } } ?> i keep getting the 500 - internal error on iis, but works on a single class file, as soon as i add more then one i get the error, can someone please help me and explain where i have gone wrong. thanks, all. Please help. I have tried to condense the following code to make it easier for someone to shed insight. The results make totally no sense to me.
I have the following two lines of code: require_once('/var/www/bidjunction/application/classes_3rd/htmlpurifier/library/HTMLPurifier.auto.php'); $config = HTMLPurifier_Conf::createDefault();Let me explain what happens in these two lines of code. First.... require_once('/var/www/bidjunction/application/classes_3rd/htmlpurifier/library/HTMLPurifier.auto.php'):HTMLPurifier.auto.php is shown below: <?php /** * This is a stub include that automatically configures the include path. */ set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() ); require_once 'HTMLPurifier/Bootstrap.php'; require_once 'HTMLPurifier.autoload.php'; // vim: et sw=4 sts=4The only thing Bootstrap.php does is define a class and execute the following line: define('HTMLPURIFIER_PREFIX', realpath(dirname(__FILE__) . '/..'));The only thing HTMLPurifier.autoload.php does is execute HTMLPurifier_Bootstrap::registerAutoload() (which was one of the classes defined in Bootstrap.php). The only thing HTMLPurifier_Bootstrap::registerAutoload() does is: spl_autoload_register(array('HTMLPurifier_Bootstrap','autoload'), true, true);Now the second line: $config = HTMLPurifier_Conf::createDefault();I expected that HTMLPurifier_Conf::createDefault() would be executed, but no, instead the script goes to HTMLPurifier_Bootstrap:autoload() which returns false. Next, the script goes to function PHPMailerAutoload() which is in PHPMailerAutoload.php. What!!! What does PHPMailerAutoload have to do with this? While a perfect answer would be great, general comments and a strategy to troubleshoot be the next best thing. I am stumped! Please help. Hello, I'm new to the forum and I'm looking for advice. I use a bunch of classes in namespaces that are I'm attempting to organize for autoloading. In other words, a class called \Foo\Package\Class is loaded from the file at Foo\Package\Class.php. I'm using spl_autoload for this. (If I were on 5.2 I could be using underscore-delimited pseudo-namespaces just as well; the implementation detail isn't important) Now, I want to have multiple separate apps that use a single common library. Each app also has some classes that are local to it. How should I solve the autoloading problem? I thought of the following approach. Is it any good? Try autoloading from the common class library If it fails, try autoloading from the app's own local library Part 2 of the question: Within my apps, though, there are two types of classes: library ("vendor") classes that are only being used in that particular app so they don't need to be in the shared library, and app-specific classes that are the core of the app (so they, by definition, don't need to be in any shared library). I'd probably like to keep these two separate, so I'd need to add point #3 to the list above: search in the "core" class hierarchy of the local app. This gives 3 separate locations, and the problem is that they negate the advantages namespaces since there can be overlap. In which case one class will override the other during autoloading. So order of the above list would matter. And time would be wasted looking for a class in the first two places if it's more often in the third. A solution I was considering is sticking to just one central library of classes (and dumping all app-local libraries there). Then, the core classes that belong to one app would be under an \AppName namespace. I'm looking forward to some insights from the experts. How do you guys organize your class libraries? I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Evening, So I have three files. run.php Code: [Select] // autoload the classes function __autoload($className) { include "class.".$className.".php"; } // setup the sessions handler $session = new Session($member); // setup the handler $handler = new Handler(part, template, $_GET); The handler takes the $_GET data and includes the templates header -> $_GET matching body file -> footer and returns it forming a page. However. When I go to call something from the Session class for example in the body file with... body.tpl.php Code: [Select] <?=$Session->isLog();?> I get... Code: [Select] Notice: Undefined variable: Session in .../body.tpl.php on line 12 Fatal error: Call to a member function isLog() on a non-object in .../body.tpl.php on line 12 It is my understanding that the class is ready for use, but isn't? I'd really appreciate any advice you can spare. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. |