PHP - Are 'registry' Classes Good Practice?
I'm trying to teach myself OOP PHP, and I've been looking up a number of tutorials on how to to make OOP MVC frameworks. I came across this one (cached version - their site is down at the moment of posting), and noticed something interesting about it that I've not seen in other tutorials.
Basically, it creates a registry class as $registry (which just uses the __set and __get functions to populate an initially empty array), and then stores variables in there. After that, $registry is passed on to the other classes via their __construct functions, so that they can access site-wide variables.
I think I understand how it's working, and see how it can be used, but this tutorial is the only time I've found such a thing. I was wondering, is using such a class good practice, or how should I store and access globally needed variables (like configuration, database connections, etc)?
Similar TutorialsHi I am looking to develop a public facing website and would like some good practice info on php, what you should and shouldnt do and which way to do things, e.g. for security and efficiency, etc. I have read through the PHP security guide from the PHP Security Consortium and was really good, does any one have any more info like this regarding PHP and general good practice Thank you hey guys i used defined variables inside my index.php and these defined varaibles are called and used through the site...is this good or bad? defined varaibles Code: [Select] define('DS', DIRECTORY_SEPARATOR); define('PARENT_DIRECTORY_PATH', dirname(dirname(__FILE__)) . DS); define('PUBLIC_DIRECTORY', BASE_URL . DS .'public' . DS); define('PRIVATE_DIRECTORY', BASE_URL .'private' . DS ); thank you I'm reading over this book and I came across something that looked very odd:
public function DisplayHeader() { ?> <table width="100%" cellpadding="12" cellspacing="0" border="0"> <tr bgcolor ="black"> <td align ="left"><img src = "logo.gif" /></td> <td> <h1>TLA Consulting Pty Ltd</h1> </td> <td align ="right"><img src = "logo.gif" /></td> </tr> </table> <?php }In the function it closes a php tag, uses raw html that is rendered as is on the page, and then returns back to opening the php tag. I understand why it is being done. It is easier to write raw html here than to echo it in a php block, but it just looks odd. Anyone actually use this technique? I have a long list of variables with form fields inserted into them like this: $page_id = $_POST['exclude']; I just turned on WP_Debug just to see which error messages would come up and to my surprise it wasn't that bad, the most error messages were "Call to Undefined function". The solution to this problem is simple, all I have to do is wrap an isset around all the form field variables, like this: $page_id = isset($_POST['exclude']); My question is, is this really necessary or considered as good practice? Should I now go ahead and wrap to all the variables in that long list an isset around? Or should I just turn WP_Debug off again and leave it as is? I personally would like to adopt to the good practice way, but I don't know how much of an advantage it is to wrap an isset around every single form field variable. Any suggestions? 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 am making some kind of licensing system and want to read a key value from the registry that identifies the PC of the client. I found some code on the internett, but which doesn't work, and I was hoping someone could explain me why. I want to read the key from the following address: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid. I am fully aware that this value can be changed, but I can use it anyway. I have found two methods. The first is the following: $Wshshell= new COM('WScript.Shell'); $data= $Wshshell->regRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid'); echo $data; And this is the second one: $keyhandle = reg_open_key('HKEY_LOCAL_MACHINE', 'Software\Microsoft\Cryptography\MachineGuid'); $value = reg_enum_value($keyhandle,1); echo $value; What am I missing to make these work, or are there other way to do it? Thanks in advance. Sincerely hey guys im having an error whilst trying to return an object registered in my registry class. Quote Notice: Trying to get property of non-object in C:\www\private\application\models\league_model.class.php on line 10 the object in trying to get is a config document reader which should return things such as database details and setting of the website. if someone could help me please that would be excellent...i hope you understand Index - where the resigtry is made Code: [Select] $config_root = 'config' . DS . 'config.ini'; $document = new Document; $config = $document->read($config_root); $registry = new Registry(); $registry->config = $config; Model - where the config is called but returns an error Code: [Select] $config = Registry::get_instance()->config; echo $config->db_username; Registry class Code: [Select] <?php class Registry { static protected $_instance = null; protected $_objects = array(); static public function get_instance() { if (self::$_instance == null) { self::$_instance = new self(); } return self::$_instance; } public function __set($key, $object) { $this->_objects[$key] = $object; } public function __get($key) { if (isset($this->_objects[$key])) { return $this->_objects[$key]; } return NULL; } } ?> return of the instant $this->_objects within the Registry class Code: [Select] Array ( [config] => Document Object ( [_values:protected] => Array ( [developement_enviroment] => true [db_type] => mysql [db_host] => localhost [db_username] => root [db_password] => password [db_database_name] => test [default_controller] => news [default_action] => articles [autoloader_ignore_directories] => Array ( [0] => .buildpath [1] => .project [2] => .settings [3] => . [4] => .. [5] => tmp [6] => views [7] => public [8] => scripts [9] => .htaccess ) ) ) } ) :-\Have been reading a few places about how to set php.ini file to be able to use MySQL on my Yahoo website. But am also warned to avoid tampering needlessly with registry. So I need an absolute precedure, with port 465, I also know. Embarassing how long this has taken me to find some of this out! Thanks, Yshua Trying to improve my script-architecture, I got curious about other ways to pass application-data around aside from using the$GLOBALS array. The only other way I really found was to use an object called a "Registry". I just ended up being confused regarding when which method is better than the other, let alone how to even use a registry-object in my scripts. So my questions a - When is it better to use a registry object in place of global data? - how would you use a registry? - how would a registry object get passed around, through other objects and functions? Heres the registry I found... class registry { var $_cache_stack = array(); function __construct(){ $this->_cache_stack = array(array()); } function set($key, &$item){ $this->_cache_stack[0][$key] = &$item; } function &get($key){ return $this->_cache_stack[0][$key]; } function isEntry($key){ return ($this->getEntry($key) !== null); } function &instance(){ static $registry = false; if (!$registry) $registry = new Registry(); return $registry; } function save(){ array_unshift($this->_cache_stack, array()); if (!count($this->_cache_stack)) exit('Registry lost!'); } function restore(){ array_shift($this->_cache_stack); } } Not sure how to describe what I'm trying to do here in the title, but here goes with what I am trying to accomplish. I've got a few hundred lines of code in total so far, so I'll try to keep it as short as I can. I've got an application that I am programming using classes for each module and right now I am coding the base classes that I need in order for it to run (database, errors, logging, etc). What I'm doing for my database class is I have a query factory and it extends the MySQLi class so I can process, clean and code the rest of my app faster. I also have another, unrelated class "Error", which will be used for processing errors I might come across. I'd rather do it this way instead of having to call trigger_error and error_log every time there is an error. I'd also not like to have to call a new instance of an object every time I need to use something from that class. Is there any way I can call a class within a class and return it as an object for all the methods within the class? I've tried the methods below, but no luck I've tried others, but I'm trying to keep it brief and get what I'm trying to do across. <?php class QueryFactory extends MySQLi { public $err = new error(); //Doesn't work. public $err = error(); //Nope. #This is the function that I need the $err object for. function set($fields, $newvals) { if ( is_array($fields) && is_array($newvals) ) { if ( count($fields) != count($newvals) ) { //Instead of below, I want to do something like $err->('Array lengths must match for method', 256, $islogged = 1); trigger_error('Array lengths must match for method', 256); } } } } The thing is, I have a "run.inc.php" which does include and create new objects for running just the basic app and if I try to redeclare the error class in query.class.php, it gives me an error saying I can't do that, but if i try to call $err from the page that has all the classes defined it throws an error saying that my method is undeclared. I'd like my error class be available to every other class I create so I can display and log errors as needed. Any suggestions or links to point me where I'd like to go? Hi. I've been learning OOP and watched a video on YouTube about a "secure" OOP PHP login script. It was pretty good, and helped me to understand some OOP approaches, but I couldn't help thinking some of it was wrong. I'm not sure so feedback appreciated! The class starts of something like this: Code: [Select] <?php class Login { private $_id; private $_username; private $_password; private $_passmd5; private $_errors; private $_access; private $_login; private $_token; public function __construct() { $this->_errors = array(); $this->_login = isset($_POST['login'])? 1 : 0; $this->_access = 0; $this->_token = $_POST['token']; $this->_id = 0; $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username']; $this->_password = ($this->_login)? $this->filter($_POST['password']) : ''; $this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password']; } Isn't "hard" setting variables, like the POST vars in the contruct bad? Shouldn't they be passed through elsewhere? I've learnt that OOP needs to be reusable and manageable as it's primarily the point of using OOP in the first place. I might be wrong but I noticed straight away that the above class doesn't seem reusable (in the true sense). Hopefully i'm getting the hang of it... Thanks mysql_query("INSERT INTO people (company, lname) VALUES ('clean($_POST[Company])', 'clean($_POST['lname'])' "); using a clean function in the query instead of doing it before hand? Until participating and reading this topic, I had though the following code was perfectly fine. I don't claim to even be good at OOP or application design, although I would like to be lol Anyway, the only functionality regarding google maps polylines I could think of in PHP, was encoding and decoding them, so I placed them in a static class: <?php /* -- Polyline.class.php @return string (encoded lat/lng) - polyline::getEncoded(-2.5675, 2.5456); @return string (encoded lat/lng's) - polyline::getEncoded(array(-2.5675, 2.5456), array(-2.5675, 2.5456)); @return string (encoded lat/lng's) - polyline::getEncoded(-2.5675, 2.5456, -2.5675, 2.5456); @return array (decoded array(lat, lng)'s) - polyline::getDecoded('zmtn_?_epn_?zmtn_?_epn_?zmtn_?_epn_?'); */ class Polyline { private static $_calls = 0; private static $_lastLat = 0; private static $_lastLon = 0; // public accessors public static function get_encoded() { // $encoded to store encoded points $encoded = ''; $args = func_get_args(); if ( is_array($args[0]) ) { while ( list($k, $arg) = each($args) ) $encoded .= self::_encode($arg[0]) . self::_encode($arg[1]); } else { $cnt = count($args); if ( !$cnt ) return false; $i = 0; while ( $i < $cnt ) $encoded .= self::_encode($args[$i++]); } self::$_calls = 0; self::$_lastLat = 0; self::$_lastLon = 0; return $encoded; } public static function get_decoded($str) { $points = array(); $lat = 0; $lon = 0; while (strlen($str)) { $lat += self::_decode($str); $lon += self::_decode($str); $points[] = array($lat * 1e-5, $lon * 1e-5); } return $points; } // private private static function _encode($dec) { $dec = round($dec * 1e5, 0); if ( !(self::$_calls % 2) ) { //lon if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLon; self::$_lastLon = $dec; } else { //lat if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLat; self::$_lastLat = $dec; } $dec = isset($ndec) ? $ndec : $dec; $is_neg = stristr($dec, '-'); $dec <<= 1; // invert bits if negative if ( $is_neg ) $dec = (~$dec); //0 pad to 32 bits $dec = str_pad(sprintf('%b', $dec), 30, '0', STR_PAD_LEFT); // chunk into 5 char strings and reverse $dec = array_reverse(str_split($dec, 5)); // or with 0x20 except last one ( add 63 to each and convert to ascii ) $c = count($dec); for ( $i = 0; $i < $c; ++$i ) $dec[$i] = (isset($dec[$i+1]) && $dec[$i+1] & 31) ? ((bindec($dec[$i]) | 32) + 63) : (((bindec($dec[$i])) > 0) ? bindec($dec[$i]) + 63 : ''); // set times called self::$_calls++; return vsprintf('%c%c%c%c%c%c', $dec); } private static function _decode(&$str) { $shift = 0; $result = 0; $i = 0; do { // while ascii($str[$i++]) > ascii([space] " ") $b = ord($str[$i++]) - 63; $result |= ($b & 0x1f) << $shift; $shift += 5; } while ($b >= 0x20); $str = substr($str, $i); return (($result & 1) ? ~($result >> 1) : ($result >> 1)); } private function __construct() {} private function __clone() {} } ?> not that it matters much, since the rest of the application in which this class resides went to design shit, but; is this bad practice in your opinion? Hi,
I study a php book and every thing is going fine, the problem is that I dont know how to practice what I study...
iv'e searched alot in the internet of exercise and found few but not every thing there is the same as what I study and sometimes they ask me to do things that I dont know yet..
some people saying that you need to think about a project and start building it but I dont have enough knowledge so start build something on my own..
right now I know about if/else, loops, operators, functions and objects, arrays, date and time, and file handling.
so most of the exercise I find involving mysql that I dont know yet.
can someone give me tips maybe how he started to study php?
it will help me alot and im sure it will help to more people.
thakns in advance,
guy.
Hi, (Apologies in advance if this is a total newbie question - if it is, just give me some idea on what I need to search for!) I have written php code that essentially pulls together multiple records (using mySQL) and displays them in a webpage. The challenge I have now is making the output pretty. What is the best way to do this? I have my css file (with several styles in the format below): Code: [Select] .textstyle0 {font-family:Tahoma;font-weight:normal;font-style:normal;font-size:48px;text-decoration:none;color:#ffffff;} div.Object50 { position:absolute; padding-right:5px; top:189px; left:92px; z-index:0; text-align:left; width:437px; } And my html file (that I want to bring in the php output): Code: [Select] <div class="Object50"><span class="textstyle0">Q. THIS IS A TEST?<br></span></div> My php code is sitting in a tidy block: Code: [Select] $result = mysql_query("SELECT * FROM tbl_scores WHERE ID=$f_id") or die(mysql_error()); $row = mysql_fetch_array( $result ); $f_score = $row['score']; $f_freq = $row['freq']; echo "test" . $f_score; Do I need to update all my php code with the relevant css tags or can I reference the php? Or do I split up my php code? Do I leave my php code at the top and store all the values somewhere? Then these get pulled into html? I guess I am trying to reduce how much of the php coding I need to modify while leaving the flexibility in the design.... Hey everyone,
I am working on a project for fun. This is a LAMP application that is going to run on my intranet server, and hold NO VALUABLE data. I am doing it just to get better at programming, and learn some best practices and techniques. at this point, I am working on some things, and I don't know what the best practices are. Can someone help me go down the pest route?
1. A log-in system and I want to include a "remember me" button. What is the best practice for this? Obviously leaving user data in a cookie is asking for trouble, so I was thinking of leaving a unique id of some sort? 2. Information in a login SESSION. What information do you put in a log in session? I have seen lots of different techniques on this. I don't really know which is the best. For the moment, I keep an array like this: array('Status'=>True, 'Username'=>'Users name" ,'email'=>'users Email'). If a hacker can inject session information, this seems like it would be really easy to break, because they only need a user's name and email to gain access. Is there something more I should do? 3. Config file that holds Mysql Information. I made a file that contains all the values that might change over time. That way I only need to change it in one spot. In this file I have things like the Mysql Database information. Should these files be encrypted? Or can I use a .htaccess file to make sure it isn't accessible to a hacker (as I mentioned before, this isn't a project that's going live, its more of an exercise to help me learn)
Thanks everyone Hi Guys, I have a query regarding best practice for performance on a web application I'm developing. I am retrieving data via an API that I then need to display on a website. The data retrieved all relates to a product ID. The issue I am having is that each product has a UniqueID, but also a GroupID. The GroupID is used to display the same products but of different colour/size combinations. ie. UniqueID GroupID Size Colour 1 1 n/a n/a 2 2 Small Red 3 2 Medium Blue 4 2 Large Green I need to display the products in a list, but where there are multiple products in a group, I need to provide a dropdown selector for size and a dropdown selector for colour. I'm struggling a bit with how to structure it with just the array spat out by the API, so I was considering saving the data to a MySQL database and then querying that to get what I need. Is this a good way to go or is the double query hit going to be horribly inefficient? Cheers! 2 PART QUESTION (so I don't have to ask two questions 😀 )
1.)
2.) On my particular coding, I can use either the NULL/isset style, or, the ""/== style, with no errors or ill effects.... but something tells me the expert PHP coders prefer one over the other... Thank you!! Edited July 10 by ChenXiuI don't really have an issue with my script... I simply want to know if it is a bad practice to create a script that recurses through your root directory and zips up everything into one large zip file... I am creating a backup deal for my site and my site is rather large... Is this considered bad practice? Hi guys, so I tried searching this, but I had some issues being able to find the proper wording and keywords to query. Everything I searched PHP, HTML, Coding Standard, Coding Style, Coding, Style, Standard, etc. I got varying results. With that being said, if anyone knows of a topic that already addresses this, please feel free to link it and I will gladly do the footwork.
^ TL;DR --> I searched, but couldn't find a topic for this...
Alright, now down to the brass tacks... I am having some trouble building a function in PHP that will display the header. I believe (if I am not mistaken) that I have seen people warning against peppering PHP code with echo <HTML HERE> throughout your code. I can sort of understand why, but I admit I am not completely sure why this is. I am trying to figure out a way to display HTML without doing the following...
<?php // -------------------------------------------------------------------------- // ADMIN BAR HANDLER // -------------------------------------------------------------------------- /** * First we need to determine if the user * is logged in or not. After determining * the user's logged in status, we will then * choose to display the admin bar or * redirect the user to the login page. */ function admin_bar() { if ( defined( USER_IS_LOGGED_IN ) ) { echo "<div class='admin_bar'> Admin Bar Here </div>"; } else if ( defined( USER_IS_NOT_LOGGED_IN ) ) { header( "Location: " . LOGIN_PAGE ) ; } } ?> |