PHP - Best Way To Organize Namespaced Classes In The Filesystem? (autoload Question)
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? Similar Tutorialshello, 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 i have questions on how to create a file system server. were you clients could upload files and download their files in the future. Is this professional to store the files in database I am working on my Pool class (base) and my FootballPool class (derived). I have this as my constructor Pool.php protected $pid, $uid, $pkid, $name; function __construct($pid, $uid){ $this->pid = $pid; $this->uid = $uid; $this->pkid = $this->pkid(); if(isset($_SESSION['picksInfo']['name'])) $this->name = $_SESSION['picksInfo']['name']; else $this->name = NULL; } Now a function in my FootballPool class needs to call $pid, $uid, and $pkid. How can I do that? I have tried this: Pool::$pid, but then I get this error Quote Fatal error: Access to undeclared static property: Pool::$pid in /var/www/core/includes/FootballPool.php on line 31 I am confused, because in the parents constructor, it is set. So basically, how can I call a variable set in the base class from a child or derived class? Hi everyone, Until now i didnt use classes and functions for sql related actions and now i would like to start. I started out with this : class.php --------------------------------------------------- class db { public function connect($database,$user,$password) { $db = mysql_connect("localhost",$user,$password) or die (mysql_error()); mysql_select_db($database); } static function fetch() { function getresults($query) { $resultArray = array(); $fetch = mysql_query($query) or die (mysql_error()); while ($row = mysql_fetch_assoc($fetch)){ $resultArray[] = $row; } return $resultArray; mysql_free_result($fetch); } } } and index.php ---------------------------- <?php require('class.php'); $connection = new db(); $connection->connect("testdb","root","root"); $connection->fetch()->getresults("SELECT * FROM users"); foreach (getresults() as $user) { echo "<div>{$user['user_first_name']}</div>"; } I'm trying to implement a library which was written for PSR-0 compliant autoloading in my joomla project. However joomla 2.5 does not support PSR-0 autoloading so I figured that I would have to write my own implementation.
Since I want to use my classes across my entire joomla installation I decided to write a plugin which registers the classes onAfterInitialise() but this is where it goes wrong: it overrides joomla's autoloading methods.
The library i'm trying to implement is located at libraries/Zoho/CRM/ZohoClient.php with several subfolders. Everything is namespaced with accordance to PSR-0 so starting with: \Zoho\CRM.
How do I register the classes in such a way that I can use them globally across joomla? This is my implementation:
public function onAfterInitialise() { spl_autoload_register(function ($className) { $className = ltrim($className, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strripos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; require $fileName; }); }This obviously wont work because it overrides the joomla autoloading function. I'm running php5.3 (5.4 in 3 months) So I'm pounding away at some of the new 5.3 features to try and get a grasp on setting up a custom MVC. spl_autoload with namespaces is frikkin awesome, however im trying to make life easy by being able to drop a class file in an "objects" folder that holds all the models for the app and have the controller parse out the get request for the proper model call and dynamically create the object. Example: url = www.example.com/?auth controller parses $_GET and see's you are requesting the auth module. Now I'm having an issue instantiating a variable that has a namespace\class inside it: Code: [Select] $namespace = 'objects\\'; $clean['object'] = $namespace.key($clean['get']); $this->object = new $clean['object']; Logfile: PHP Fatal error: spl_autoload(): Class objects\\testobject could not be loaded... OK, its trying to escape the backslash? Maybe some trickery is needed? Code: [Select] $clean['object'] = $namespace.chr(92).key($clean['get']); NOPE, still the same error... Any cluepons? This may sound like a very stupid question, but I can't find a clear answer anywhere. I'm making my first dive in OOP and all the tutorials only really show basic usage. They define a class, and show how to use it in a file. My question is how does it work to use an object throughout a program? Is it available everywhere or do I store things in sessions and start a new object on each page? For example: logging in a user. If I created an instance after confirming the credentials, would that same instance be available for use in say index.php, or would I just pass a session over and create a new instance on each page? Again, sorry if this seems dumb to some people. Currently I'm learning about objects and classes. I followed a tutorial about making a DB abstraction class (a mySQL select) and then I tried to adapt it and wrote a method to Insert a new name. However, then I had a problem: what if the value already exists in the DB? So I thought maybe I could write a method for that too, and hopefully this would be re-usable for other purposes. So I'm posting the code here and I hope someone could take a look at it, since I do not want to start any bad practices and start a habit of writing sloppy code. Would the code below be considered 'good code'? <?php // This file is called database.php class database { public $mysql; function __construct() { $this->mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Database connection failed'); } /* Function to check whether value: $queriedName already exists inside table: $table and column: $column */ function findMatch($table, $column, $queriedName) { if ($result = $this->mysql->query("SELECT * FROM $table WHERE $column='$queriedName'")) { if (!$numberOfRows=$result->num_rows) { return false; } else { return true; } } } /* Function to select all records from table: $table */ function selectAll($table) { if ($result = $this->mysql->query("SELECT * FROM $table") ) { while($row=$result->fetch_object()) { $nameFields[]=$row->names; } return $nameFields; } } /* Function to insert a name: $newName into table: $table. Uses method finMatch to avoid doubles */ function insertName($table, $newName) { if ($this->findMatch($table, 'names', $newName)) { $result="Person already exists!"; return $result; } else { $result = $this->mysql->query("INSERT INTO $table(names) VALUES ('$newName')"); return $result; } // } } ?> Main page: // This file is called index.php require('database.php'); $newName='Mary Jane'; $result=$myDb->insertname('mytable', $newName); echo $result; I've been spending long hours learning about classes and their magic methods. I just came across a tutorial which showed a constructor like this:
class Device { //... public function __construct(Battery $battery, $name) { // $battery can only be a valid Battery object $this->battery = $battery; $this->name = $name; // connect to the network $this->connect(); } //... }the Battery part instantly caught my attention. Here had previously made a Battery class (and a more complete Device class) but the next thing he did really caught my interest: $device = new Device(new Battery(), 'iMagic'); // iMagic connected echo $device->name; // iMagicwhat the hell is going on here? Is this another way to include the methods and properties of one class into another class, in order words is this the same thing as: class Device extends BatteryI don't think so because this new Battery() thing looks more like its creating an object inside the Device object. Previously the only way I could to that was to type $battery = new Battery() inside one of my methods. But this looks like hes doing something different. Can anyone explain whats going on here? The whole tutorial is he http://code.tutsplus...-php--net-13085 in the main Device method he has a premade $battery variable to hold the Battery object. Sometimes I have multiple classes containing functions which I'd like to include in my main class. I can only extend one class, so I usually extent a class containing only properties, no methods. I still don't know what difference making that info class abstract is, I'd appreciate if anyone could tell me. Also I'd love to know what the point in static methods is. I've never used them because I've never seen the point. Is it just to make it easier to call the methods because you don't need to create an object instance to call them? Sorry for the extra questions, the first one is what I'm really wondering about. 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? Well 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. 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? 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??? 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. I have a connection.php for connecting to my database and I have done it this way connection.php Code: [Select] function connect() { global $mysql; $mysql = new MySQLi('localhost','cybershot','pascal35','billPay') or die('couldn not connect'. mysql_error()); } I have another file where I want to perform a query so I included the connection.php at the top of that file which I will call results.php and in the body of my results.php I have this Code: [Select] $names = $mysql->query("select * from names") or die($mysql->error); if($names){ while($row = $names->fetch_assoc()){ $name = $row['firstName']; $lastName = $row['lastName']; $company = $row['companyName']; echo $name . " "; echo $lastName . " "; echo $company . " "; } } I had to make $mysql a global variable in the connection.php in order to get it to work in another page. is there a better way to pass that variable to the results.php page? or is there a better way period? I am developing a multilingual site. I use array to save translations in one file which I include it inside settings.php. Code: [Select] //Example of english $LANG['welcome']="Welcome"; $LANG['status']="Status"; I am wondering about two things: 1. How would be the best option to print those arrays? a) Echo all html and inside html I use Code: [Select] echo " <body> <div> <p>{$LANG['welcome']}</p> </div> ";b) Close php and write html and inside html I open and close php for each time Code: [Select] <div><p><?php echo $LANG['welcome']; ?></p></div> Each one has own downsides. Option a) spends extra resources to print html. Option b) spends extra resources to close and open php each time (could means that single script needs to open and close php even 30 times per script). Is that bad or is the ammount of resources spend for this negligible? 2. Also how do you translate words inside javascript? I was thinking to put all translation that are need for javascript into $LANG['js'] array. Then I would use at the head of the script foreach $LANG['js'] to print html to assign javascript language variables. Code: [Select] <script type="javascript"> <?php foreach($LANG['js'] as $keyword => $translation){ echo "var ".$keyword."= ".$translation.";\n"; } ?> </script>Is there any better way? Thank you! Hi every one, i want to know, how do i autoload my class file in each page without using include directive. Thanks 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. I am looking at making a photogallery system for an online community based site. I know that we need to have unique id's , photo names and albums. What i am looking for is: Would it be recommended to create a directory for each user once they are registerd? How would you go about naming and sorting photogralleries? How would you go about naming you photos? How would you do it? I was thinking about a uuid kind of code: ( from php.net) Code: [Select] class UUID { public static function v3($namespace, $name) { if(!self::is_valid($namespace)) return false; // Get hexadecimal components of namespace $nhex = str_replace(array('-','{','}'), '', $namespace); // Binary Value $nstr = ''; // Convert Namespace UUID to bits for($i = 0; $i < strlen($nhex); $i+=2) { $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1])); } // Calculate hash value $hash = md5($nstr . $name); return sprintf('%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" substr($hash, 0, 8), // 16 bits for "time_mid" substr($hash, 8, 4), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 3 (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" substr($hash, 20, 12) ); } public static function v4() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } public static function v5($namespace, $name) { if(!self::is_valid($namespace)) return false; // Get hexadecimal components of namespace $nhex = str_replace(array('-','{','}'), '', $namespace); // Binary Value $nstr = ''; // Convert Namespace UUID to bits for($i = 0; $i < strlen($nhex); $i+=2) { $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1])); } // Calculate hash value $hash = sha1($nstr . $name); return sprintf('%08s-%04s-%04x-%04x-%12s', // 32 bits for "time_low" substr($hash, 0, 8), // 16 bits for "time_mid" substr($hash, 8, 4), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 5 (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, // 48 bits for "node" substr($hash, 20, 12) ); } public static function is_valid($uuid) { return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'. '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1; } } // Usage // Named-based UUID. $v3uuid = UUID::v3('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString'); $v5uuid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString'); // Pseudo-random UUID $v4uuid = UUID::v4(); hello dear php-developer and fans
see the page http:www.literaturen.org
on wp version 4.0 i run several amazon-plugins that fetch data from amazon.
note; the side runs the responsive-pro-theme.
question -
is it possible to organize the first or the first and (!) the second posting as a two collum posting
in other words; i want to show some bookreviews - on the page - t
i want to add two books side by side in the first posting and i want to add two books side by side in the second posting is this doable: see - as a example the site: http://www.wittwer.de/ http://bookshop.pear...gabandon=AW; note : see the two collumn with the book-presentation - at the top site. love to hear from you greetings |