Re: [PHP] Class constants
On Mon, Apr 19, 2010 at 7:25 AM, Peter Lind wrote: > Per the PHP manual: "The value must be a constant expression". Is > something that depends on other classes, variables or functions > constant? > When I came up against this problem myself, I read "a constant expression" to mean "an expression involving only constants". I think that's a fairly reasonable parse of the phrase. Thus I expected to be able to combine other constants using the dot operator as Gary is trying to do. Obviously, it didn't work, and I removed the "base" constant and replicated its value in the other constants--a situation constants were designed to obviate. Gary, you'd probably be better off asking for the technical reason behind this limitation on a -devel list. :) -- David Harkness Senior Software Engineer High Gear Media, Inc.
Re: [PHP] Re: What's your game? (X-PHP)
Left 4 Dead 2, by far my favorite game on the PC, is my current fixation. I enjoy Battlefield 2: Bad Company but tend to get annoyed having to face opponents 5-10 x my level. You can find me as Captain Cujo on both games. On Sun, Apr 25, 2010 at 10:37 AM, Nathan Rixham wrote: > however, there is one > caveat which is Civilization 4 (which i haven't played for about 2 years > now) > If you'd like to enjoy Civ4 again, might I humbly suggest you grab The BUG Mod (BTS Unaltered Gameplay) if you have the Beyond the Sword expansion pack. It doesn't alter any game rules as the name suggests, but it vastly improves the user interface. BAT includes BUG plus a bunch of nice terrain and civilization-specific graphics to make it very pretty if your video card is more modern. I'm EmperorFool, the lead developer on the BUG team. There are other quality game-changing mods for Civ4 such as Legends of Revolution, History of Three Kingdoms, Dune Wars, and Rise of Mankind that add more spice to the game.
Re: [PHP] create tree from arrays
Shahrzad, While your algorithm is correct it is very inefficient. The full array is scanned for every element in the array. If the array contains 1,000 elements, 1,000,000 comparisons will be performed and mktree_array() will be called 1,000 times. This is known as order n squared: O(n^2) and is about as slow as it gets. Oh, I see that you "have to use [a] recursive function." Is this is a homework assignment? If not and you want to make it faster, you can speed up the code by creating a new array first that maps from $a['nid'] => $a (the array element) to create a hash table. Then loop over the array again and use the hash table to find the parent of each element ($a) and add it to $a. This will be much faster without being any more complex (exchange recursion for two simple loops). Peace, David
Re: [PHP] create tree from arrays
On Mon, May 17, 2010 at 9:13 AM, Richard Quadling wrote: > OOI, can you take a look at my first response. Is this the sort of > thing you were talking about? > Essentially, yes. For the temporary array I would map nid => element instead of INDEX => nid. Your $Relationships array is basically the same as $Data. The goal is to make the lookup of parentID fast. This would be automatic if the keys of $Data were the nid values instead of a raw index from 0..N-1. If the relationship INDEX = nid - 1 for all elements in $Data, the temporary array also isn't needed. Here's how I would code it: function makeTreeAndReturnRoots(&$arr) { // not necessary if $arr is guaranteed to contain at least one root $map[0]['children'] = array(); // map each nid to its node foreach ($arr as $index => &$node) { $map[$node['nid']] = $node; } // add each node to its parent's children array foreach ($map as $nid => &$node) { $map[$parentID]['children'][] = $node; } // return the array of root nodes return $map[0]['children']; } Note: I haven't tested the above so my reference usage may be off, but it illustrates the basic algorithm. Each node requires a single ArrayPut operation to create $map and a single ArrayGet to lookup the parent node in $map in addition to the two attribute accesses for nid and children (also ArrayGet operations). Since all of the keys are unique in their respective hashtables, these operations should all be O(1) making the entire algorithm O(2n) which simplifies to O(n). David
Re: [PHP] is
On Thu, Jun 10, 2010 at 3:34 PM, Ahmed Mohsen wrote: > I know that i should use the full open tag in php but i want to > know if its good to use this tag instead of > According to some PHP 6 will remove support for short tags. They won't be disabled by default--the feature simply won't exist. http://www.slideshare.net/thinkphp/php-53-and-php-6-a-look-ahead David
Re: [PHP] is
On Thu, Jun 10, 2010 at 4:49 PM, Daniel Brown wrote: > You'll still see short_open_tags, That's good to hear. Not that we're in any rush to jump into PHP6 given that we're only just now *close* to deploying 5.3. > but you'll no > longer have ASP-style tags or the little-known
Re: [PHP] is
On Fri, Jun 11, 2010 at 11:16 AM, Ashley Sheridan wrote: > For which can cause issues when outputting the XML declaration line unless > it's broken into two parts, which is messier than ' Can you give an example of how this breaks? I don't see any problems with ' ?> unless you are trying to validate your PHP script as XML. Given that PHP is *not* XML I don't know why you'd want to do that. But I've seen this argument a few times while looking into this issue so maybe I'm just not seeing the big picture. David
Re: [PHP] is
On Fri, Jun 11, 2010 at 2:51 PM, Ashley M. Kirchner wrote: > They had every single file starting with: > > > *PHP* files? I would have flagged that as the problem rather than disabling short tags. David
Re: [PHP] Static Class Member References
Ah, so assigning a reference to a variable already holding a reference changes that variable's reference only in the same way that unsetting a reference doesn't unset the other variables referencing the same thing, yes? $a = 5; $b = &$a; print $a; > 5 unset($b); // does not affect $a print $a; > 5 // and according to Mike's previous message $b = &$a; $c = 10; $b = &$c; // does not affect $a print $a > 5 That makes a lot of sense. If it didn't work this way there would be no easy way to untangle references. In the case of foreach($array as $key => &$value) { ... } the first value in the array would continuously be overwritten by the next value. 1. $value gets reference to first array value 2. on each step through the loop, the first array value would be overwritten by the next value in the loop since $value is forever tied to it by the initial reference assignment. That would be a Bad Thing (tm). Thanks for the clarification, Mike. David
Re: [PHP] Does class length slow down performance
On Thu, Jul 22, 2010 at 2:40 AM, Ashley Sheridan wrote: > The larger a script or class is, the more memory this uses per instance. > This is not quite true. When the script is loaded, it requires a fixed amount of memory to parse it. The larger it is, the more memory it requires. Next, the script itself is executed, running any top-level code (not in a class or global function). If that includes any require/include statements, those scripts are loaded (if necessary). If it creates objects, that takes more memory. However, the size of each instance of the class is affected only by the data it stores--not the number or length of its methods. PHP creates a single internal Class object to contain the methods, and this indeed takes memory proportional to the number of methods, but this doesn't affect the instances. Each instance stores only its instance properties such as $this->firstName. This correction aside, the advice here is spot on: split your classes based on responsibilities. The reason for this has more to do with ease of development than performance. Say you have one monster class filled with static methods. If your application uses most of those methods for each request, splitting it will have no performance benefit because both scripts will end up being loaded anyway. But if you can group the methods into logical subsystems, they will be easier to understand and work with. Peace, David
Re: [PHP] Re: Does class length slow down performance
On Sat, Jul 24, 2010 at 5:57 AM, Nathan Rixham wrote: > If you think about it, each class, function, method, line of code all gets > interpreted in to opcodes and executed - so, no matter how you split it up, > it's still going to produce roughly equivalent opcodes. > An exception to this is when you have a class that can be heavily refactored. For example, say you have a data access class that operates on books in the database (standard CRUD) and also generates XML and JSON views of the books. If you refactor the class to extract the XML and JSON export into separate classes--something that should be done for many other reasons--you won't have to load and parse that code when you're not exporting the data. David
[PHP] PHP 5.3 as a requirement for a library?
I'm working on the Hamcrest matching library and have been considering the switch to using namespaces (\Hamcrest\Type\IsInteger) instead of class-names-as-namespaces (Hamcrest_Type_IsInteger). Coming from the Java world I'm used to being forced to deploy my applications on versions one or two behind the latest stable release. It was common to run on 1.2 when 1.4 was available and 1.3 when 1.5 was available for over a year. Managers are fearful of new versions. Is this same pattern repeated in PHP? My current company just switched to 5.3 after running 5.2 for some time. Are we average in that regard or the exception to the rule? Peace, David
Re: [PHP] logical AND assignments
The reason for "and" to have such a low precedence is so you can use it to perform conditional processing. You can probably achieve every effect using "&&", but you'd need more parentheses. More typically you would use "or" in this fashion: defined('DS') or define('DS', DIRECTORY_SEPARATOR); This checks if DS is defined and defines it if not. APP_ENV != 'prod' or die('This feature must not be used in production'); If we're in production, stop execution with an error. Using || here would try to logically or the string 'prod' with the return value of die(). Of course, die() doesn't return, so the script would exit no matter what APP_ENV was set to. David
Re: [PHP] logical AND assignments
On Wed, Sep 8, 2010 at 9:55 AM, Peter Lind wrote: > || and && would work exactly like 'or' and 'and' in the above. ==, !=, > === and !=== have higher precedence than || or && > Ah, you're correct. The only operators between &&/|| and and/or and the ternary ?: and assignment operators. Thus the need for the parentheses in $Condition2 = (true and false); to make $Condition2 false. The parentheses in $Condition4 = (true && false); are redundant since && has higher precedence than = (assignment). Robert, how do the results differ from your expectations? David
Re: [PHP] re: logical AND assignments
On Fri, Sep 10, 2010 at 8:22 AM, Robert E. Glaser wrote: > It's hard to wrap my mind around the concept that the assignment > operator itself has an operator precedence. Which means that one could > write expressions without any assignment at all, and be syntactically > correct. > You do this all the time without realizing it! echo "Hello, " . $name; $rect->setTopLeft(new Point(5 * 3, 2 / 3)); These expressions are eventually assigned to function parameters or passed to the PHP engine in the case of echo, but there are no assignment operators present. And all of the control structures--if, while, for, etc.--take expressions. Expressions are all around us. You can feel them when you go to work . . . when you go to church . . . when you pay your taxes. No wait, that's the Matrix. David
Re: [PHP] Zend framework
We use part of Zend MVC (the dispatcher, controllers, and view scripts) here and a lot of the other facilities such as the autoloader, config, etc. and are very happy so far. As long as you design your application with an eye toward portability, you won't be tied to ZF. For example, put all of your business logic in model classes instead of the controllers themselves. That way if you ever need to move to a new presentation layer or use the business logic outside it (e.g. in SOAP or RPC messages), you'll be ready. David
Re: [PHP] Re: Xpath arguments in variable
And let's not forget $v = $row->xpath("//membernumber[. = \"$MemberId\"]"); The \" inside the string turns into a double-quote and using " to delimit the string allows for variable substitution.
Re: [PHP] Re: Xpath arguments in variable
On Thu, Sep 16, 2010 at 1:20 AM, Pete Ford wrote: > On 15/09/10 18:00, David Harkness wrote: > >> $v = $row->xpath("//membernumber[. = \"$MemberId\"]"); >> > > Oooh, I hate using backslashes - they always seem so untidy... > I have a pathological fear of sed scripts, too. :( And yet I find them the *most* tidy in a way: \" inserts an actual double-quote into the string. I don't think that's any more magical than "surround it with single-quotes so it doesn't terminate the string." It will work in single- and double-quoted strings equally, so you don't have to worry about switching from one to the other messing up the expression. David
Re: [PHP] Re: Which PHP 5.3 documentation generators have you found?
While we don't use any 5.3 specific features such as namespaces yet, we set up our continuous integration system to use Doxygen. It runs significantly faster than phpDocumentor, though we put zero effort into tuning either system.
Re: [PHP] Re: Is it possible to create a global namespace alias?
On Tue, Oct 5, 2010 at 8:41 AM, Matt Palermo wrote: > I'm assuming there is no way to make a global alias. Can anyone > confirm/deny this? > I reread the documentation on namespaces, and from what I can tell this is no way to do it. Each file maintains its own active namespace *at compile time*. This means you can't even get around it with eval() or including another script to set it. I can't say I'm positive someone won't find a way around it, but short of an extension I don't see one. David
Re: [PHP] Variable (Class instantiation) collision
If you have total control over application A which contains the bridge code, the easiest is to change it to use a different global variable, $dbA. This must not be doable or you wouldn't have asked. If you have control over the bridge code, and it alone calls A and B, then you could swap the $db variables between calls: $db = null; $dbA = null; $dbB = null; function copyPersons() { useA(); $persons = loadPersonsFromA(); useB(); savePersonsInB($persons); } function connect() { global $db, $dbA, $dbB; connectToA(); $dbA = $db; unset($db); connectToB(); $dbB = $db; unset($db); } function useA() { global $db, $dbA; $db = $dbA; } function useB() { global $db, $dbB; $db = $dbB; } This is the simplest implementation. You could get trickier by tracking which system is in use and only swapping them as-needed, writing a facade around the APIs to A and B. It's ugly, but it works. David
Re: [PHP] Casting from parent class to child
Casting does not change an object. You must copy the relevant value(s) from the object returned into a new DateTimePlus. Since DateTime's constructor takes only a string, and I assume it won't accept your format directly, you're better off converting the string into a Unix timestamp and creating a new object from that. However, I leave that optimization to you. The following code is sufficient: $plus = new DateTimePlus(); $plus.setTimestamp(parent::createFromFormat("H.i d.m.Y", $string).getTimestamp()); return $plus; David
Re: [PHP] What other languages do you use?
On Fri, Oct 8, 2010 at 10:30 AM, Nathan Rixham wrote: > As per the subject, not what other languages have you used, but what other > languages do you currently use? > At work: PHP and Java mostly with some Javascript and BASH scripting thrown in for good measure. We use PHP for the website and Java for the deployment/tools platform and any backend system that needs multithreading. At play: Python and C++ for BUG Mod (Civ4 mod). Learning Lua for Civ5 but have been too busy lately. :( David
Re: [PHP] RegExp question: how to add a number?
On Thu, Oct 14, 2010 at 1:42 PM, Andre Polykanine wrote: > But (attention, here it is!) if the string starts with > something like "Re[4]:", it should replace it by "Re[5]:". > Regular expressions do not support any mathematical operations. Instead, you need to use preg_match() to extract the number inside the brackets, increment it, and build a new string using simple concatenation (.). elseif ($start=="re[") { if (preg_match('/^re\[(\d+)\](.*)/i', $f['Subject'], $matches) > 0) { $f['Subject'] = 'Re[' . ($matches[1] + 1) . ']' . $matches[2]; } else { // no closing brace -- now what? } } David
Re: [PHP] simple class & constructor
Note that you still have a typo, but maybe it's only in your email messages: class simpleConstructer { function __construct() { echo "running the constructor"; } } $test = new simpleConstructor(); The class is misspelled; it should be simpleConstructor. As a side note, it's common convention to name classes with a leading capital letter, e.g. SimpleConstructor. That's just convention, though, and I'm sure it differs in some languages. Even in PHP stdClass doesn't, but most other classes do. David
Re: [PHP] simple class & constructor
The "constructor" is the __construct() method, and it gets executed automatically when you instantiate the class into an object. The class defines the state (fields/properties) and behavior (methods/functions) that its objects will have. Instantiating the class is the fancy term for creating a new object with that state and behavior and calling the class's constructor on it. From then on you can call other methods on the object and access its public state. David
Re: [PHP] Re: Possible foreach bug; seeking advice to isolate the problem
On Wed, Oct 20, 2010 at 5:00 AM, Tommy Pham wrote: > Shouldn't that be $row = null since unset will remove the last value, not > just removing the variable also, from the array whereas the $row = null > will > tell the reference pointer that it doesn't point to a value. > No, that would assign null to the last array element. References allow you to assign any value--including null--to the container they reference. Unsetting a reference breaks the reference without affecting whatever it references. $x = 5; $y = &$x; $y = null; print_r($x); var_dump($x); --> NULL David
Re: [PHP] Re: Possible foreach bug; seeking advice to isolate the problem
On Wed, Oct 20, 2010 at 11:08 AM, Tommy Pham wrote: > hmm.. About 8-9 years ago I did a project where I used the reference > in a foreach loop as the OP. unset not only remove the variable but > also the value in the array. I tried several methods at that time and > ended up assigning null to get what I wanted without modifying the > array. I'll have to dig up that project later to see. > To be thorough, I ran the same test as above using unset(), and it correctly clears the reference and leaves $x in tact. $x = 5; $y = &$x; unset($y); var_dump($x); --> 5 var_dump($y); --> NULL It's quite possible this behavior was changed along the way. I started using PHP last year with 5.2. David
Re: [PHP] Re: Possible foreach bug; seeking advice to isolate the problem
On Sat, Oct 23, 2010 at 6:48 PM, Jonathan Sachs <081...@jhsachs.com> wrote: > Now that I understand it, I can see the same thing would happen if I > wrote the equivalent code in C, and probably in Java. > Neither C nor Java have references as PHP does, and references in C++ cannot be changed to point to a new location after being created. None of these languages have this particular quirk. If you use pointers in C or C++, the way you assign an address to a pointer makes it clear you are not overwriting whatever the pointer currently points to, so again it's not a problem. In PHP we have a very common pattern of using a reference in foreach(), and the loop variable continues to reference the last item after the loop exits. Further, the second loop has to use the iteration variable as a non-reference. If both loops use a reference variable, the problem disappears: $x = array('a', 'b', 'c'); foreach ($x as &$i) echo $i; > abc foreach ($x as &$i) echo $i; > abc In my opinion, if you write code where a variable is a reference at point X and a non-reference at point Y, you are asking for trouble. Simply separate the loops into different functions or introduce a new loop variable. David
Re: [PHP] Implementing optional methods in a concrete class, but calling them from an abstract class.
On Mon, Nov 1, 2010 at 10:42 AM, Andrew Ballard wrote: > Right up to here, it sounded more like an interface than an abstract base > class. > I think there's an interface in there *and* a basic (HTTP? RPC?) implementation that receives and dispatches the messages. I would split these responsibilities into two separate classes which would allow you to wire up the services to different dispatchers over time. But to your original question, Richard, I agree with Nathan. Go with the solution that is both easy to code and and easy to read, especially given that the API is quite static. David
Re: [PHP] Help with variable variables not being set for a multi-dimensional array
On Tue, Nov 9, 2010 at 6:55 PM, Daevid Vincent wrote: > I've used variable variables before but for some reason I can't figure this > snippet out. Why doesn't $ini_file get set (or appended to). > AFAIK variable variables can only reference actual variables--not array subscripts or other non-variable syntax elements such as "->" or "::". eval() can do this because it parses the code as PHP. Variable variables take the *variable name* contained in the variable and look it up in the current scope. This is a variable name: ini_array This is not: ini_array['agis_core']['adapter'] I think you can use references here to do what you need. Warning: I only tested the basics of this in the interpreter without running this exact code. public function explode_ini() { $ini_array = array(); foreach($this->ini_array as $heading => $key_vals) { foreach ($key_vals as $k => $v) { $path = &$ini_array[$heading]; $subsection = explode('.', $k); foreach ($subsection as $ss) $path = &$path[$ss]; $path = $v; unset($path); } } $this->ini_array = $ini_array; } David
Re: [PHP] DOMDocument/DOMElement problem
On Wed, Nov 17, 2010 at 10:27 AM, Peter Lind wrote: > Quick note, in case anyone has similar problems: make sure that the > data you feed into DOMDocument is UTF8 encoded > I can attest to this as well. I just fixed a bug in our sitemap-building code that was producing some items with empty titles for Google News. it turned out they had smart quotes from Word in them because the title field wasn't being passed through the filter. Once I filtered and converted to UTF-8, all is well again. The strange thing is that we just upgraded to PHP 5.3, and I can't believe no one had accidentally pasted in a smart quote before the upgrade. We're running 5.3.3 in fact, and I wouldn't be surprised if something changed in DOMElement. David
Re: [PHP] Procedural Autoloader?
On Mon, Nov 22, 2010 at 12:37 PM, Jason Pruim wrote: > The autoloader function that is in PHP 5+ works on classes... But I'm not > finding anything that would do the same thing on the procedural end. > I'll start by explaining how it typically works with classes. The Zend Framework is a popular web/application class library. It organizes its classes into packages much like Java, Python, and other languages, where each package is a folder that contains other packages and classes. In Java, packages are a language feature so you have java.util.List which is the fully-qualified name of the List class that lives in the java.util package. PHP doesn't have the notion of packages, though 5.3 introduced namespaces which are similar but different. The autoloader function in PHP takes a class name and locates the file that should define it. In Zend this is done by separating the folder names by underscores, e.g. Zend_Http_Request. The autoloader splits the class name on underscores and looks in registered folders for a folder named Zend, and inside that for another folder named Http, and inside that for a file named Request.php. Zend's autoloader class provides more features such as aliases for folders so "ZF" would map to "Zend". The above is based on the convention of having one class per file. I doubt you'll be doing that for functions, so even if PHP had an autoloading mechanism for functions, you'd still need a way to map from function name to file name. I suppose you could do the same as above but drop the final name element when looking for the file. For example, the function math_trig_cos() would map to the function cos() defined in "math/trig.php". But it's all academic because PHP does not support such a feature. You could probably create a PHP extension if you wanna roll up your sleeves and get dirty in C. :) David
Re: [PHP] Procedural Autoloader?
The simplest solution would be to move those functions into static methods of classes. Place one class in each file to organize your functions and use an autoloader to load the classes. You don't need to instantiate the class to use the autoloader--just reference it statically: // library/Math.php class Math { const PI = 3.14159; public static function sin($radians) {...} } ... $x = $radius * Math::cos(Math::PI * 0.5); David
Re: [PHP] Procedural Autoloader?
On Mon, Nov 22, 2010 at 3:05 PM, Richard Quadling wrote: > Would it be overboard to use a namespace? Aren't namespaces handled by > the autoloader? If not autoload(), how about spl_autoloading? > Autoloading is for determining the path and filename where a named item is defined. Namespaces only give you the path. Even with namespaces, you'd still need to require the files that contain the functions. Plus you'd also need to use the namespace everywhere you use the function because you cannot alias functions--only classes. :( David
Re: [PHP] new keyword combined with other things...
On Tue, Dec 7, 2010 at 1:55 PM, Paul M Foster wrote: > Here is an example from their [CodeIgniter] user manual: > > $this->db->select('title')->from('mytable')->where('id', $id)->limit(10, > 20); > This is known as a "fluent interface" because it attempts to make your code read more naturally--i.e. fluently. Each method returns either a new object or the same object ($this) so it can flow into the next method call. In the latter case, the initial object stored in $this->db implements all the above methods. I first saw this in mock object libraries for Java, but it was invented years earlier. $mock = $this->getMock('Calculator'); $mock->expect('add')->once()->with(3, 5)->willReturn(8); David
Re: [PHP] PHP4 to PHP5 migration with E_STRICT
In getCategoryTypes() you're assigning a reference to the return value of getContentTypes(), and PHP doesn't like that. You can return a reference to a variable from a function, but taking the reference of a *value* is meaningless since you can only create references to variables. Just remove the & on that marked line to get rid of the warning. Also, I notice that both of those methods (and I assume many more) take a reference in $db. Note that all objects are assigned by reference in PHP 5, and thus the & here is unnecessary since you are passing an object to these methods and aren't changing the reference inside the method. Note that PHP won't issue a warning for these since it is acceptable and you might want to point the reference to a new object inside the function. You aren't doing that here, so the & is superfluous and misleading. David
Re: [PHP] new keyword combined with other things...
On Wed, Dec 8, 2010 at 9:31 AM, Paul M Foster wrote: > I agree. My advice for SQL is always to learn SQL rather than use a > bunch of active record functionality. But I'm sure people think I'm just > a curmudgeonly old turd. ;-} > Yes, absolutely learn SQL so you understand what's happening under the covers, AND then use a framework to abstract much of it away. I cannot speak to ActiveRecord, but ORM frameworks like Hibernate in the Java world save countless man-hours of work every day, time that can be spent on making better applications. On Wed, Dec 8, 2010 at 7:14 AM, Tommy Pham wrote: > The only need I see for this is to build the query dynamically... > which should be very rare since all those function calls are > expensive, IMO. > Function calls haven't been expensive since 1992. ;) The cost of running the SQL query itself will dwarf any function calls made to build the query. The gains in developer productivity vastly outweigh the small gains to be had by micro-optimizing away function calls and other abstractions, and developer time is much more expensive than CPU time. Start with code that is easy to understand, write, and debug. Measure the performance if it is too slow, find the slow parts using a profiler, and optimize them. Nine times out of ten you can gain more by changing your algorithm than by removing function calls. David
Re: [PHP] how can one run python script in php
On Wed, Dec 8, 2010 at 2:50 PM, Moses wrote: > I am trying to run a python script in php using exec or system command, but > there is no answer. > If you post the code you have tried, we can point out any errors you're making and help you find the solution. David
Re: [PHP] ORM doctrine
On Wed, Dec 8, 2010 at 11:11 PM, Daevid Vincent wrote: > Avoid these ORM things like the plague! . . . Not to > mention all that fancy "ORM" doesn't come without a price. It costs in > terms > of speed, as well as training. > If you value CPU time over developer time, by all means avoid ORM frameworks (and *all* frameworks). The point of a common framework is to trade a small bit of performance for a large amount of developer time. If you will only use the framework once, the payoff will be much less. The goal is to choose frameworks that you can leverage again and again. As for training, you will be able to hire another developer that knows Doctrine. It will be impossible to find a developer *anywhere* that understands your home-grown framework without training. Nor will you get help with bugs in your framework or be able to discuss better ways to use it on forums. That being said, there are times when it's better to write your own code. I will do this if the options out there don't suit my needs or if they seem under-supported. For example, while we use PHPUnit and Zend MVC in our apps, I wrote my own TestCase subclasses instead of using Zend's. I had to write documentation for the other developers, and I must maintain it as needs change. It was not a decision I took lightly. David
Re: [PHP] ORM doctrine
On Thu, Dec 9, 2010 at 7:41 PM, Daevid Vincent wrote: > I disagree. If you use a framework, then you're stuck with it. Bugs and all > (and trust me there are bugs and limitations you WILL run into). I have fixed bugs locally in third party libraries; I have submitted them for patching; I have received fixes from other people for them; and I have had them accepted. This must be factored in to your choice of tool. Don't go with the project that hasn't had any commits in over a year. Also, projects lead by a single person with no other committers bring risk. > If it's your code, you can fix it. > If it's your code, you are the only eyes looking at it and the only one that can fix it. It's a trade-off. Doubtful. It's hard enough to find skilled PHP developers as it is. > If that's the case, you're already behind the eight ball. Whether you use someone else's code or your own, they won't be able to learn it. At least with an outside tool there's a slim chance they've worked with it before. That's just it. DO NOT make a "framework". Make some helper routines for > common tasks like sql_query(), sql_insert(), sql_update(), > sql_select_box(), etc. and stick to the "basics". > This discussion started about ORM, and I think we've moved on to third-party libraries. By using "framework" as you have, you're narrowing the conversation considerably to a handful of libraries at most (Zend, Cake, any others for PHP?). By framework I mean a collection of related helper routines, classes, methods, etc. that make performing a specific access of coding easier. [I wrote] > > Nor will you get > > help with bugs in your framework or be able to discuss > > better ways to use it on forums. > > That's what your employees, team-mates, customers, testers, etc. are for... > I prefer my network of help to include thousands of coders rather than a handful. If you're making "JoeBlowsRinkyDink.com" then go for the framework if you > want to play with it for the massochistic experience and to learn your > lesson the hard way. But don't use it for paying customers and certainly > don't use it in an enterprise level -- it will be the death nail to your > project ultimately. > I've successfully used frameworks for small customers, large customers, in the enterprise and at startups. I've also written my own libraries to perform more narrow tasks in the same environments. Use the right tool for the job; don't be dogmatic in your decisions or you'll end up wasting time or other resources. To bring this back around to ORMs specifically, if you are going to build a lot of database-driven applications and you want to use object-oriented techniques rather than passing around a bunch of arrays, take some time to investigate the options. If you find a tool you like, your time investment to learn it will pay off in spades with each new project. You only need to learn it once; it will save you time again and again after that. David
Re: [PHP] Use PHP the way God intended...
On Mon, Dec 13, 2010 at 8:48 PM, Paul M Foster wrote: > Nah, if he'd read it backwards, you'd be able to hear MePHPistoPHPeles > say, "Rasmus is the Penguin". > > (Yes, you have to be dang old to get that obscure reference. ;-) > Pshaw, not *that* old! I get the reference, and I'm only . . . oh, damn. :( David
Re: [PHP] Use PHP the way God intended...
On Tue, Dec 14, 2010 at 8:43 AM, Paul M Foster wrote: > Er... that's Paul McCartney, not Paul Foster. Whew! > Paul McCartney's dead?? But the Beatles just released a ton of albums on iTunes! So sad...
Re: [PHP] How does one reply to messages on this list?
On Thu, Dec 16, 2010 at 8:09 AM, Daniel Molina Wegener wrote: > If your MUA (or email client) is smart enough, it should have at least > > "Reply", "Reply to Sender", "Reply to All" and "Reply to Mailing List". > To which my client adds "Reply to /dev/null", "Reply to Those Who Actually Care", and "Reply to Al Gore". It's much smarter than the average MUA. David
Re: [PHP] String passed to object constructor turning into aninstance of that object?
It's acting as if Tag's constructor a) declares $name as a reference using &$name, and b) is assigning itself ($this) to $name for some (probably bad) reason. That's the only way I can see that $name inside SelectBoxOption's constructor could change from a string to an object. A peek at Tag's constructor could really clear things up. David
Re: [PHP] String passed to object constructor turning into an instance of that object?
I've never used the old-style constructors, but perhaps the semantics of "parent::" changed and you need to instead use "$this->" as in $this->Tag("option", $name); That's a total guess. I don't have 5.2 handy to try it out, but both work in 5.3 using a simple example. Can you post the constructor of one of the Tag subclasses that work? Maybe we can find a common denominator. David
[PHP] Does ReflectionMethod::setAccessible() do anything?
According to the manual page for setAccessible() [1] the feature is available with 5.3.2, and I'm running 5.3.2-1ubuntu4.5 with Suhosin-Patch (cli) (built: Sep 17 2010 13:49:46) so I should be good to go. However, even the simplest test to make a protected or private method accessible fails. php > class Foo { protected function bar() { echo "foobar\n"; } } php > $m = new ReflectionMethod('Foo', 'bar'); php > $m->setAccessible(true); php > $foo = new Foo(); php > $foo->bar(); Fatal error: Call to protected method Foo::bar() from context '' in php shell code on line 1 I've tried creating the object first, getting to the ReflectionMethod via ReflectionClass::getMethod(), and making a public method inaccessible, but all fail. Has anyone used this feature? The reason I want to do this, in case anyone can suggest a work-around, is to allow direct unit testing of protected/private methods in classes. What I do now is have a function that eval()s a dynamic subclass with a __call() method that proxies to protected methods. This doesn't allow testing private methods, and it breaks if the class under test has a private/protected constructor. I can solve the second problem with some further hacking, but there's nothing I can do about exposing private methods temporarily. setAccessible() seems perfectly designed to do what I need. Thanks, David [1] http://php.net/manual/en/reflectionmethod.setaccessible.php -- David Harkness Senior Software Engineer High Gear Media
Re: [PHP] Problems w/ goto
On Fri, Dec 17, 2010 at 10:05 AM, la...@garfieldtech.com < la...@garfieldtech.com> wrote: > What PHP has implemented is "named break statements", as I understand it. > Not exactly. You can jump to arbitrary (labeled) lines within the same context (method/function), but you cannot enter loop constructs--only exit them. While the last bit implies they are only "named break statements," you can use them outside of loops as a normal goto statement. firingSequence: if (!acquireTarget()) goto done; fireMainCannon(); fireMissiles(); if (enemiesInView()): goto firingSequence; done: The above implements a convoluted do...while loop using goto. Recommended? Certainly not! David
Re: [PHP] Does ReflectionMethod::setAccessible() do anything?
On Thu, Dec 16, 2010 at 6:09 PM, Nathan Nobbe wrote: > you just have to invoke the function from the context of the > ReflectionMethod instance > > class Foo { protected function bar() { echo "foobar\n"; } } > $m = new ReflectionMethod('Foo', 'bar'); > $m->setAccessible(true); > $m->invokeArgs(new Foo(), array()); > ?> > Thank you, Nathan. That makes perfect sense and would be a good addition to the documentation page for setAccessible(). Even better, I may even be able to make use of it in my testing framework since I only want the method to be exposed for one call from the test method. David -- David Harkness Senior Software Engineer High Gear Media
Re: [PHP] Does ReflectionMethod::setAccessible() do anything?
On Thu, Dec 16, 2010 at 6:09 PM, Nathan Nobbe wrote: > you just have to invoke the function from the context of the > ReflectionMethod instance > > class Foo { protected function bar() { echo "foobar\n"; } } > $m = new ReflectionMethod('Foo', 'bar'); > $m->setAccessible(true); > $m->invokeArgs(new Foo(), array()); > ?> > Thank you, Nathan. That makes perfect sense and would be a good addition to the documentation page for setAccessible(). Even better, I may even be able to make use of it in my testing framework since I only want the method to be exposed for one call from the test method. David -- David Harkness Senior Software Engineer High Gear Media
Re: [PHP] Problems w/ goto
On Mon, Dec 20, 2010 at 7:45 PM, David Hutto wrote: > Is the problem with using the goto convolutedness(as I've seen other > senior programmers in other languages when explaining, or 'showing > off'), or is their an actual functional problem with it? It works perfectly well and is a great solution in extremely limited cases. The problem is that it can be used in many cases where other control flow statements are more clear. It was more of a problem before because people came from languages that had goto but not the other high-level control flow statements. Using goto often leads to hard-to-follow code. For example, rearranging the above code yields do { if (!acquireTarget()) { break; fireMainCannon(); fireMissiles(); } while (enemiesInView()); Even this doesn't get away from using break--a special form of goto for loops. One way around that is to introduce a loop variable like $done, but I think break is cleaner here. Sometimes goto, break, and continue are simply the best tools for the job. I wouldn't say "never use goto," but I do feel that 99 times out of 100 you're probably better off using something else. One thing to keep in mind is that under the hood the PHP interpreter turns while(), for(), etc. into a bunch of gotos. for ( ; ; ) is just a shorter way to write goto check; loop: check: if () goto loop; The same can be done for all the other control flow statements. David
Re: [PHP] Is there a simple way to enforce a private method in a subclass?
On Tue, Dec 21, 2010 at 8:36 AM, Richard Quadling wrote: > If I have an abstract class of Task and I want all subclasses of Task > to have a private method _runTask, is there a way to enforce this? > I cannot think of a reason to force a class to have a specifically-named *private* method. Since it's private, you cannot call it from outside the class--not from its superclasses nor any subclasses. Since it cannot be exposed in the class's API, there's no point in forcing a particular name. If you are using the Template Method pattern [1], make the method protected. This allows the superclass that declares the abstract method to call it and forces its subclasses to implement it given the name you decide. David [1] http://c2.com/cgi/wiki?TemplateMethodPattern
Re: [PHP] accessing magic parent set
On Wed, Dec 22, 2010 at 6:35 AM, Alexandru Patranescu wrote: > Is this the only way to access the magic __set from the parent class: > >parent::__set($columnName, $value); > Other than referencing the parent class by name which is worse, yes. > I would have liked to work this way: > >parent::$columnName = $value; > The problem is that attributes are all attached to the object instance ($this). Only those that were defined by a class are associated with it. The "parent::" construct is used only to locate the method overridden by the current method. There is a self, a static and a parent > Why is it only $this and not a $parent too? > I would guess the reasoning is that $this is a value (an object instance) whereas the others are not. David
Re: [PHP] Static content at runtime
The other option is to generate the page dynamically and cache it (we use Varnish) for the next users. This way you pay the cost to regenerate pages only for those someone views--and only once. This pays off well when you have high traffic. David
Re: [PHP] Re: Do you trim() usernames and passwords?
On Tue, Dec 28, 2010 at 3:28 PM, Paul M Foster wrote: > Users would be wise to follow a scheme like > this, rather than using their dog's name or somesuch as their passwords. Aww man, I've been using "somesuch" as the password for all my accounts and now you've ruined it! Luckily I use your dog's name for my bank passwords which is probably still safe. To address the OP, I would agree with skipping trim on both the user name and password. If it's a copy-paste error, they will try again. If you want to get fancy, warn when the password starts with or ends with spaces if it comes back incorrect, but I think that's probably going to be so rare as not to be worth the extra effort. David
Re: [PHP] Newbie Question
On Wed, Jan 5, 2011 at 8:20 AM, tedd wrote: > I teach using NetBeans, because it generally sucks less than Eclipse. > Eclipse is simply too complicated and NetBeans tries to be less, but it's > still too much. > Have you tried PHPStorm? I installed it but haven't had a chance to play with it yet. Despite the name, I believe it is designed to handle (X)HTML, JavaScript, and CSS as well. I use and prefer Eclipse for Python and Java code, but I found its PHP support severely lacking the last time I checked (a year ago?). However, at this new job since I do mostly PHP I stick to NetBeans even when working in Java occasionally. It's just easier to use the same tool since all the menus and key commands are just different enough. I can't objectively comment on which layout is better. I prefer Eclipse, but I used it for a few years before trying NetBeans and am simply more comfortable with it. Both are great and horrible at the same time. :) I do have to say that NetBeans more than Eclipse will randomly become unusable for unknown reasons: disk and CPU activity spike, code-completion lags, whatever. Eclipse seems more solid in this regard. David
Re: [PHP] Unload/reload included class
On Tue, Jan 4, 2011 at 4:44 PM, Patrik Pomichal wrote: > Loading plugin is easy, when my app found new file in plugins dir, > include and register it. But if i change the plugin source i must restart > the app to reload it. If you don't mind the resource burn (memory) of loading a lot of code over time without flushing it out when not needed, you could have the plugin files contain the methods without the enclosing class declaration. When you (re)load a plugin, you create a dynamic class name using a counter or some other uniqueness mechanism, build a string containing a class declaration wrapped around the file's contents, and use eval() to load it. You could of course let the coder put a class name into the plugin file if that looks nicer and do a string replace on it with your dynamic name. The key is that you cannot unload classes in PHP AFAIK so you must come up with a new class name each time. The old compiled bytecode will remain, but you can destroy the old plugin instance to regain a little memory. David
Re: [PHP] Newbie Question
On Wed, Jan 5, 2011 at 10:35 AM, Daniel Brown wrote: > On Wed, Jan 5, 2011 at 11:32, David Harkness > wrote: > > I do have to say that NetBeans more than Eclipse will randomly become > > unusable for unknown reasons: disk and CPU activity spike, > code-completion > > lags, whatever. Eclipse seems more solid in this regard. > > Whereas, on Linux, I've found the exact opposite to be true: > NetBeans seemed to work fine, while Eclipse would lock. > I used Eclipse on Windows and only a short while on Ubuntu, and I've used NetBeans exclusively on Ubuntu. I actually switched to using the beta and now dev builds of NetBeans because of the issues I mentioned. To this day when I'm editing PHP files, the disk is hit with every keystroke. This doesn't happen for any other file type such as Java. There's no good reason that I can think of for that, and it's quite annoying. That said, I only use IDE's when I want to see what's new in the > world, or to see if I could speed up my own development processes at > all. There are so many helpful additions to modern IDEs that I miss when I drop into basic editors. The key is integration. When I'm editing a file, the IDE shows me which lines have been modified, added, and removed. I can hover over the indicator to see the original text or revert the change. You can get this information outside the editor, but I find it speeds up my work to have it in one place. Of course, I often find myself using grep instead of the IDE's "find in files" feature. ;) Old habits die hard. I will admit that I never got to be much of an emacs or vi power user, and I'd bet they have a lot of the IDE capabilities I have grown to love. I also have poor vision requiring larger fonts for the main text area, and most IDEs (GUIs really) provide more tools for me to mitigate the problem than a fixed terminal. David
Re: [PHP] Newbie Question
On Wed, Jan 5, 2011 at 3:05 PM, tedd wrote: > I spent a couple of hours reviewing PHPStorm and it looks *very* promising! Thank you for sharing your thoughts on PHPStorm. My main performance gripe with NetBeans has lessened in the year I've been using it, so I'm less inclined to go up yet another learning curve, but it's always helpful to get input on the competitors. Please let us know if you end up using it in your class as I'm sure others will enjoy reading your findings. I spent about 10 minutes looking over the feature set of Komodo which was recommended by Steve Staples in this thread, and it also looks quite impressive. it's more expensive for the IDE (the stand-alone editor is free) which does remote file-syncing ($295), but you might be able to swing an educational discount with them. Most companies will gladly give their product away to put it in the hands of soon-to-be-professionals. :) Good luck! David
Re: [PHP] Global or include?
On Wed, Jan 5, 2011 at 3:27 PM, Nathan Nobbe wrote: > if($cachedConfig !== null) > { >// load file and store value(s) in $cachedConfig > } > "No config for you ... one year!" Sorry, couldn't resist. :p To expand on Nathan's excellent strategy, you could go one further and add functions to config.php to return specific values from the config instead of exposing the raw config object. This will have benefits if you change the structure of the config later and only have to change your access code in one place. It also replaces client code such as $config = load_config(); if ($config['facebook']['enabled']) { ... } with the more readable if (isFacebookEnabled()) { ... } by adding an access function in config.php: function isFacebookEnabled() { $config = load_config(); return (bool) $config['facebook']['enabled']; } You would still require_once 'config.php', but now you don't have to expose knowledge of the config's internal structure to every script that needs to access it. David
Re: [PHP] PHP Docs update
I filed a bug report for this, but I'll put it here as well in case it helps. When you zoom in to increase the text size, the right margin increases unnecessarily. This shrinks the width of the center content column which makes reading the documentation and code snippets difficult. The right margin should remain fixed at the edge of the window. Thanks, David
Re: [PHP] Memory_Limit adjustments
The memory limit only blocks PHP from allocating more than that amount of memory for a single process (i.e. client request). Given that you're barely scratching the surface of your 2GB of memory, if you don't expect too many 17MB file uploads to happen at the same time from different users, you should be okay. If you get a lot of large file uploads in clusters, you may end up rejecting requests from clients trying to upload small files. I suppose this isn't much worse than rejecting all large file uploads, and will stop happening once those large files are completed. David
Re: [PHP] magic getter
If you want to block setting of public properties on your class, implement the magic setter. class Foo { private $data = array(); function __get($name) { return $this->data[$name]; } function __set($name, $value) { if ($name != 'foo') { $this->data[$name] = $value; } } } $f = new Foo; $f->x = 5; echo $f->x; // "5" $f->foo = 'bar'; echo $f->foo; // Notice: Undefined index: foo in php shell code on line 1 Enjoy! David
Re: [PHP] Regex
On Fri, Jul 27, 2012 at 10:16 AM, Ashley Sheridan wrote: > "Simon Dániel" wrote: > > >#[0-9a-zA-Z,\.]# > > You should escape out that period as it will match any character otherwise > The dot only matches a period inside a character class [...]. David
Re: [PHP] Re: Regex
On Fri, Jul 27, 2012 at 11:43 AM, Al wrote: > "%[\w\d,.]%" > "\w" will match digits so "\d" isn't necessary, but it will also match underscores which isn't desired. David
Re: [PHP] PHP session variables
On Wed, Aug 8, 2012 at 8:24 AM, Ansry User 01 wrote: > I am setting the _SESSION variables in one of my file, but whenever I > leave the php page session variables are not accessible. As always, post some code demonstrating what you're doing. Help us help you! :) David
Re: [PHP] Two ways to obtain an object property
On Wed, Aug 15, 2012 at 1:28 AM, phplist wrote: > I can have a User object method "getSubscriberStatus()" which sets > $this->isASubscriber. But to use this I would have to run the method just > before the if statement. > > Or I could have a method "isASubscriber()" which returns the result, > meaning the if statement should be > if ($crntUser->isASubscriber()) {...} I assume that the decision isn't really about using a property versus a method but that determining the value of the property is costly. For these cases I add an internal private property to save the result of the costly computation and initialize it on the first call to the accessor method. class User { private $_isSubscriber = null; public function isSubscriber() { if ($this->_isSubscriber === null) { $this->_isSubscriber = ... call database or whatever takes so long ... } return $this->_isSubscriber; } } If this isn't the case and you really just want to know which API is nicer, any of the replies so far are acceptable. I favor accessor methods because it's easier to change the implementation without having to change all the places you access it. Peace, David
Re: [PHP] include selectively or globally?
On Tue, Aug 28, 2012 at 4:39 AM, Matijn Woudt wrote: > First of all, I believe [A] PHP is smart enough to not generate bytecode > for functions that are not used in the current file. Think about the > fact that you can write a function with errors, which will run fine > until you call the function. [B] (except for syntax errors). [B] negates [A]. PHP must either parse the file into opcodes or load them from APC and further execute the top-level opcodes. That means defining functions (not calling them unless called directly), constants, global variables, classes, etc. No amount of measuring is required to tell me that doing X vs. not doing X in this case clearly takes longer. Now, is that time significant enough to warrant the extra logic required? In my case, absolutely. We organize our library into many classes in multiple files. By using an autoloader, we simply don't need to think about it. Include bootstrap.php which sets up the autoloader and include paths. Done. In the case with a single 50k library file that is used on 10% of the pages, I'd absolutely require_once it only in the pages that need it without measuring the performance. It's so trivial to maintain that single include in individual pages that the gain on 90% of the pages is not worth delving deeper. Peace, David
Re: [PHP] include selectively or globally?
On Tue, Aug 28, 2012 at 12:11 PM, Matijn Woudt wrote: > On Tue, Aug 28, 2012 at 6:55 PM, David Harkness > wrote: > > On Tue, Aug 28, 2012 at 4:39 AM, Matijn Woudt wrote: > >> > >> First of all, I believe [A] PHP is smart enough to not generate bytecode > >> for functions that are not used in the current file. Think about the > >> fact that you can write a function with errors, which will run fine > >> until you call the function. [B] (except for syntax errors). > > > > [B] negates [A]. PHP must either parse the file into opcodes or load > them > > from APC and further execute the top-level opcodes. That means defining > > functions (not calling them unless called directly), constants, global > > variables, classes, etc. > > [B] does not negate [A]. There's a difference between parsing the > syntax and defining functions, classes constants and globals, and > generating bytecode. In a 'normal' file I guess syntax definitions are > only about 5% of the total contents, the rest can be ignored until > being called. > I won't claim a deep understanding of the PHP internals, but I have enough experience with varied compiled and interpreted languages and using PHP and APC that I'm confident that the process to include a file involves: 1. Load the opcodes A. Either read the file from disk and parse the PHP into opcodes, or B. Load the cached opcodes from APC. 2. Execute the top-level opcodes Any syntax errors--even those in unreachable code blocks--will cause the script to fail parsing. For example, if (false) { function foo() { SYNTAX ERROR! } } will cause the parse to fail even though the function cannot logically be defined. PHP doesn't even get that far. PHP Parse error: syntax error, unexpected T_STRING in php shell code on line 3 > "When answering this question, please approach the matter strictly from > a caching/performance point of view, not from a convenience point of > view just to avoid that the discussion shifts to a programming style > and the do's and don'ts." While out of convenience you might be tempted to include the file in every script, when considering performance alone you should include the file only in those scripts that will make use of its contents. Peace, David
Re: [PHP] Static constructor support
On Wed, Sep 26, 2012 at 2:29 PM, Yves Goergen wrote: > How do other languages than C# call that? :-) > Java has "static initializers" which work the same way: they are executed when the class is first loaded and before any code can make use of the class. David
Re: [PHP] Late static binding behaves differently in PHP 5.3 and PHP 5.4
Hi Keven, First, I don't see any late static binding being used here. LSB only applies when you access a static member using the static keyword within a class method. This code uses static properties but accesses them directly without going through class methods. Here's an example of LSB: class Foo { static $my_var = 'The Foo'; static function dump() { echo static::$my_var . "\n";// Use Foo's or Bar's depending on what appears before ::dump() } } class Bar extends Foo { static $my_var = 'The Bar'; } Bar::dump();// The Bar Foo::dump();// The Foo Here Foo::dump() uses LSB to pick the source of $my_var. That being said, what you're seeing does look like a change (or bug) in how PHP accesses constants. Given that it is order-dependent, my guess is that 5.4 introduced a bug that causes Bar to push its constant up into Foo. The strange thing is that the constant is compiled into the class, and since Bar extends Foo I would expect Foo to be compiled first regardless of the order in which you access the static variable later. David
Re: [PHP] Does Scope-Resolution Operator Always Follow 'parent'?
Hi Eric, On Sun, Mar 10, 2013 at 8:21 PM, Eric James Michael Ritz < lobbyjo...@gmail.com> wrote: > I have a question about the `parent` keyword: is there any valid > situation where it can appear without the `::` operator following? > I wouldn't have thought it possible, but I just found one case with PHP 5.4 where it can appear as the keyword without a trailing "::". Apparently you can use it to instantiate the parent class just as you can with "new self". class Foo { } class Bar extends Foo { public function foo() { return new parent; } } I think you'll be safe if you can highlight it only when preceded by "new" or followed by "::". David
Re: [PHP] Mystery foreach error
On Wed, Mar 13, 2013 at 4:44 PM, Angela Barone wrote: > I ran across if(array_key_exists) and it seems to work. How does that > differ from if(isset($states[$state]))? Hi Angela, isset() will return false for an array key 'foo' mapped to a null value whereas array_key_exists() will return true. The latter asks "Is this key in the array?" whereas isset() adds "and is its value not null?" While isset() is every-so-slightly faster, this should not be a concern. Use whichever makes sense for the context here. Since you don't stick null values into the array, I prefer the isset() form because the syntax reads better to me. Peace, David
Re: [PHP] Mystery foreach error
On Wed, Mar 13, 2013 at 5:10 PM, Sebastian Krebs wrote: > Because 'null' is the representation of "nothing" array_key_exists() and > isset() can be treated as semantically equivalent. As I said, these functions return different results for null values. It won't matter for Angela since she isn't storing null in the array, though. Peace, David
Re: [PHP] Re: Is BBCode Installed
Hi Stephen, I just tried installing the PECL extension, but it failed to build on PHP 5.4.6-1ubuntu1.2. I see Xdebug in the phpinfo output, and I assume other PECL extensions will show up there once installed. Good luck! David
Re: [PHP] A Good OOP Tutorial/Read?
On Fri, May 17, 2013 at 7:04 AM, Tedd Sperling wrote: > To me there is no difference between an abstract class (without method > declarations) and an interface. > The key difference in OO languages that do not allow multiple inheritance is that you can always add an interface to an existing class but you can only mix in an abstract class if your class doesn't extend another. Let's say you want to define the contract for a UserDataAccessObject with query and CRUD methods. If you make it an abstract class, I cannot implement that contract using my AbstractMysqlDao base class. With an interface, I can do class MysqlUserDao extends AbstractMysqlDao implements UserDataAccessObject Being a dynamic language, PHP allows you to fulfill a contract without using interfaces at all. You can call findUserByLogin() on any object--even those that don't declare that interface via __call(). However, you won't be able to pass your objects to methods that use parameter type hinting. This is where interfaces really shine, and they become more important as your project grows in complexity. They are certainly *not* required to make good use of OOP, especially in PHP/Python/Ruby. However, I view an interface as a statement (a contract) where IF you want > someone to use your code you outline the methods you require them to > flesh-out in their code -- but I would like to see a simple example of > that. > Interfaces come in handy when implementing the visitor and observer patterns. Simple example are always contrived, but here's mine: interface Engine { function orderFuel(Store $store); function setSpeed($mph); } class SteamEngine implements Engine { function orderFuel(Store $store) { $store->order('coal', 1000, WeightUnit::POUND); } function setSpeed($mph) { if ($mph >= 80) { throw new InvalidArgumentException('Cannot exceed 80mph'); } $this->loadFuel(...); } } class MrFusion implements Engine { function orderFuel(Store $store) { $store->order('aluminum can'); $store->order('banana peel'); } function setSpeed($mph) { if ($mph >= 88 && empty($this->destinationTime)) { throw new IllegalStateException('Must set desired time travel destination'); } $this->adjustThrottle($mph - $this->speed); } } You could make Engine an abstract class, but that would reduce your users' choice. David
Re: [PHP] need some regex help to strip out // comments but not http:// urls
Hi Daevid, On Tue, May 28, 2013 at 2:17 PM, Daevid Vincent wrote: > I'm adding some minification to our cache.class.php . . . We have been using a native jsmin extension [1] which does a lot more without any trouble for over two years now. It's much faster than the equivalent PHP solution and is probably tested by a lot more people than a home-grown version. You might want to check it out before going too far down this path. Good luck, David [1] http://www.ypass.net/software/php_jsmin/
Re: [PHP] need some regex help to strip out // comments but not http:// urls
Hi Daevid, On Tue, May 28, 2013 at 2:40 PM, Daevid Vincent wrote: > I appreciate the pointer, but our files, like many people, is a mixture of > HTML, PHP and JS in one file. This jsmin appears to only work on .js files > right? Also, everything else works great in our minifing method, just this > edge case. My bad. We moved all our JS and CSS to external files for this very reason and created a plugin to combine and minify everything needed by each page into a unique file. While it does cause some duplication across pages, it means that every page loads exactly one JS and CSS file each. For your situation, I don't know a regular expression that will work in all cases. David
Re: [PHP] Re: need some regex help to strip out // comments but not http:// urls
On Wed, May 29, 2013 at 10:20 AM, Matijn Woudt wrote: > It is possible to write a whole parser as a single regex, being it terribly > long and complex. > While regular expressions are often used in the lexer--the part that scans the input stream and breaks it up into meaningful tokens like { keyword: "function" } { operator: "+" } and { identifier: "$foo" } that form the building blocks of the language--they aren't combined into a single expression. Instead, a lexer generator is used to build a state machine that switches the active expressions to check based on the previous tokens and context. Each expression recognizes a different type of token, and many times these aren't even regular expressions. The second stage--combining tokens based on the rules of the grammar--is more complex and beyond the abilities of regular expressions. There are plenty of books on the subject and tools [1] to build the pieces such as Lex, Yacc, Flex, and Bison. Someone even asked this question on Stack Overflow [2] a few years ago. And I'm sure if you look you can find someone that did a masters thesis proving that regular expressions cannot handle a context-free grammar. And finally I leave you with Jeff Atwood's article about (not) parsing HTML with regex. [3] Peace, David [1] http://dinosaur.compilertools.net/ [2] http://stackoverflow.com/questions/3487089/are-regular-expressions-used-to-build-parsers [3] http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
Re: [PHP] Binding object instances to static closures
On Fri, May 31, 2013 at 10:54 AM, Nathaniel Higgins wrote: > Is it possible to bind an instance to a static closure, or to create a > non-static closure inside of a static class method? > PHP doesn't have a method to do this. In JavaScript you can use jQuery's var func = $.proxy(function () { ... }, object); In fact, you cannot use $this inside a closure at all (unless 5.4 has added a way that I haven't seen yet). You can get around that by declaring a local variable to hold a reference to the instance to use with "use". It looks strange here because you're also passing in $testInstance for the comparison. createClosure($testInstance); call_user_func($closure); // should be true } private function createClosure($testInstance) { $self = $this; return function() use ($self, $testInstance) { return $self === $testInstance; } } } TestClass::testMethod(); Peace, David
Re: [PHP] Binding object instances to static closures
Thanks Nathaniel for the clarification about 5.4. We are still on 5.3 (and that only recently), so 5.4 is a ways off in our production systems. However, I'll read up on this since it may be useful in offline tools. On Fri, May 31, 2013 at 11:52 AM, Nick Whiting wrote: > TestClass::testMethod(function($param){ > var_dump($this === $param); > }); > I get why closures created inside static methods cannot be bound to an instance . . . but those created *outside* an object method entirely *can* be bound? That makes no sense! And yet it works. David
Re: [PHP] What is the name of the pattern that will ...
Hi Richard, On Thu, Jun 13, 2013 at 10:16 AM, Richard Quadling wrote: > I'm building a class which needs to have certain methods called by the > subclass, but the subclass can extend but not obscure/override the > behaviour. > This is the Template Method pattern, though in this case you could use a Strategy where the specific authentication implementation is in a separate class that gets injected into the Auth class. As for your example there a a few things I would change. * The template method that the subclass must implement should not be declared by an interface. Interfaces are for declaring public contracts. You can simply declare an abstract, protected method in Auth. This is the contract that every subclass must fulfill. * I would avoid reference variables as you've indicated. If you don't want to build a data-holder class yet, simply return an array for now. While you cannot enforce the return type at parse time, they should be verified with unit tests. Unit tests are critical with dynamic languages like PHP and Python since runtime is the only way to verify behavior. Otherwise, your example is spot on, though the name AuthRequestMade implies the request has already been made yet I think from your description that this method should *make* the actual request. Here's how I would write it with the above in place. class Auth { public function MakeAuthRequest() { // before $this->MakeAuthRequestImpl(); // Adding "Impl" suffix is a common convention // after } /** * Make the actual authentication request. * * @return array Must contain keys "state" and "message" to hold the result */ protected abstract function MakeAuthRequestImpl(); } Peace, David
Re: [PHP] Re: PHP5 OOP: Abstract classes, multiple inheritance and constructors
There's no way to bypass an overridden method using "parent", but you could add an abstract method that Child would implement. class Parent function __construct() { $this->foo = $this->getFoo(); } abstract function getFoo(); } David
Re: [PHP] Re: PHP vs JAVA
On Wed, Aug 21, 2013 at 7:56 PM, Curtis Maurand wrote: > Sebastian Krebs wrote: > Actually the problem is, that the dot "." is already in use. With > $foo.bar() you cannot tell, if you want to call the method "bar()" on the > > object "$foo", or if you want to concatenate the value of "$foo" to the > > result of the function "bar()". There is no other way around this than a > > different operator for method calls. > > I didn't think > of that. It seems to me there could be an easier operator than -> > which sometimes will make me stop and look at what keys I'm trying to > hit. Just a thought. I forgot about the concatenation operator > which is "+" in Java/C# > The PHP language developers were pretty stuck. Because of automatic string-to-numeric-conversion, they couldn't use + for string concatenation. Sadly, they chose "." rather than ".." which I believe one or two other languages use. If they had, "." would have been available once objects rolled around in PHP 4/5. I suspect they chose -> since that's used in C and C++ to dereference a pointer. > > Ever tried the jetbrains products? :D (No, they don't pay me) > > I have not, but it looks interesting. > I'll have to try it. Those are very good products which have had a strong following for a decade. The free IDE NetBeans also has quite good support for both Java and PHP, and the latest beta version provides a "web" project that provides front- and back-end debugging of PHP + JavaScript. You can be stepping through JS code and hit an AJAX call and then seamlessly step through the PHP code that handles it. I use NetBeans for PHP/HTML/JS (though I am evaluating JetBrains' PHPStorm now) and Eclipse for Java. You can't beat Eclipse's refactoring support in a free tool, though I think NetBeans is close to catching up. I would bet IntelliJ IDEA for Java by JetBrains is on par at least. Peace, David
Re: [PHP] Re: PHP vs JAVA
On Thu, Aug 22, 2013 at 12:29 AM, Sebastian Krebs wrote: > Actually I think ".." is quite error-prone, because it is hard to > distinguish from "." or "_" on the _first_ glance, which makes the get > quickly through the code. [1] > I surround all operators except member access ("." and "->") with spaces, so that wouldn't be a problem for me. I thought there was an older language that used "..", but all I can find now is Lua which was developed in the early nineties. So "." is maybe not the best choice, but also remember when it was > introduced: That was decades ago. That time it was (probably ;)) the best > choice and nowadays I don't think it is too bad at all, beside that _other_ > languages use it for other purposes now ;) > C introduced "." as the field access operator for structs in the early seventies, C++ kept it for object access, and Java adopted it in the early nineties. C's use of pointers required a way to access members through a pointer, and I suppose K&R thought "->" looked like following a pointer (I agree). Since PHP was modeled on Perl and wouldn't implement objects or structs for another decade, it adopted "." for string concatenation. It works fine, and I don't have too much trouble bouncing back-and-forth. I honestly would have preferred "." to be overloaded when the left hand side was an object. In the rare cases that you want to convert an object to a string to be concatenated with the RHS, you can always cast it to string, use strval(), or call __toString() manually. But I'm not staging any protests over the use of "->". :) > Eclipse' code-completion and debugger never worked for me well (and most > of the time: at all). It became slower and less responsive with every > release. That was the reason I decided to leave it and I don't regret it :) > I agree about the slowness, and until this latest release I've always left autocompletion manual (ctrl + space). They did something with Kepler to speed it up drastically, so much so I have it turned on with every keypress. However, it's a little too aggressive in providing choices. Typing "null" which is a Java keyword as in PHP, it will insert "nullValue()" which is a method from Hamcrest. :( After a couple weeks of this, I think I'll be switching it back to manual activation. I can type quickly enough that I only need it when I'm not sure of a method name. NetBeans, while not as good with refactoring and plugin support, is still zippier than Eclipse. And my short time with the JetBrains products found them to be fast as well. Eclipse's PHP support via PDT is not nearly as good as NetBeans, and no doubt PHPStorm beats them both. Peace, David
Re: [PHP] Static utility class?
On Wed, Sep 4, 2013 at 12:25 PM, Micky Hulse wrote: > I want to have a "utility" class that contain utility methods which should > have the option of being called multiple times on a page. > ... > To put it another way, is there any reason why I would not want to use the > above code? The main problem caused by static methods is testability. Mocking or stubbing a static method requires using a PHP extension and ensuring that the original is reset whether the test passes or fails. As long as your utility methods don't perform actions you want to avoid during tests, this is fine. Good examples for a utility class are string-processing functions such as parsing and formatting, trimming and/or normalizing empty string to null, etc. You want tests to work against these methods directly since there's no need to avoid the work. You'll want to avoid static methods whenever you want to be able to fix the behavior (stubbing) to test scenarios in the class under test. An example is anything hitting a database or external service. In order to test that your downloader sends the correct warning email to the sysadmin when a REST call fails, you need to be able to force the REST call to fail. This is easy to do when you plug in an instance implementing the API because you can give it an implementation/mock that fails for all calls. I can't say if what you're thinking of will make a good utility class since the code you posted is fake. If you post some examples of methods you want to make static, we can give you pointers on which are good candidates and which are best left to instance methods. Peace, David
Re: [PHP] PHP Dependency Injector
On Thu, Sep 5, 2013 at 1:40 PM, Juan Sebastian Scatularo < sebastianscatul...@gmail.com> wrote: > Thanks Sorin, I will do that and I will have more care the next time. You can also check out Pimple [1] by the creator of the Symfony Framework. Peace, David [1] http://pimple.sensiolabs.org/
Re: [PHP] PHPDoc way to describe the magic getter/setters [SOLVED]
On Wed, Sep 25, 2013 at 4:31 PM, Daevid Vincent wrote: > Then I randomly stumbled upon this PHPDoc @ method tag and my whole world > is brighter today than it has been for the past, oh let's say DECADE! Yes, @method and @property are very handy. Out of curiosity, since you're providing magic getters and setters, why not use __get and __set instead of __call with matching on "get_xxx" and "set_xxx"? This would allow using the simpler (and IMHO much more expressive and PHP-ish) forms $obj->foo = $obj->bar + 5; Peace, David
Re: [PHP] OO oriented PHP frameworks
On Thu, Jan 6, 2011 at 12:36 PM, Jerome Covington wrote: > I was specifically curious if there are frameworks which use the convention > of passing config objects to functions/methods in the same way that > contemporary JS libraries like jQuery do. We use Zend Framework along with its MVC framework. In the Bootstrap class initialized from index.php we load an INI file into a Zend_Config object which parses it into a hierarchical array, and store the config in the Zend_Registry--essentially making it a global variable (Singleton pattern). Instead of passing it around to the objects that need it, each class accesses it directly from the registry. While this couples these classes to the registry, it makes the code simpler. Were I to write it from scratch, I would have created a helper object that passes the config object to each controller as it's created, whether it needed it or not. That would make one class (the helper) dependent on the registry instead of every controller that accesses the config object. David
Re: [PHP] Command line PHP
On Fri, Jan 7, 2011 at 10:31 AM, Joshua Kehn wrote: > My apologies. I just view PHP as a perfected web language, due to it's > templating nature, while using it for other things (scripts, utilities, > cron) is a misuse in my opinion. > Even if you are proficient in more "CLI-appropriate" languages, there are times where you'd still choose to use PHP in this role. For example, our data access layer is written in PHP. It was an easy choice to write our sitemap-generating tool in PHP even though I am more comfortable in Java and Python. "The right tool for the job" rarely depends on only one or two factors. :) David
Re: [PHP] Command line PHP
On Fri, Jan 7, 2011 at 10:41 AM, la...@garfieldtech.com < la...@garfieldtech.com> wrote: > "Application" is perhaps a misnomer. I'm not looking at rewriting Emacs or > anything. Just some batch processing that would get run as: > > php myscript.php --config=foo.xml --setting-1=stuff For this I used getopt() which worked well enough. Long options don't work on Windows IIRC (check the docs), but you can easily get arguments from short options. An example for the tool I wrote is src/sitemap.php -s 28372 -d mydomain.com -l debug -p -z 9 -b sitemaps -o xml The code that parses the options is very straightforward. If you already use Zend Framework, it has its own CLI library I think. David
Re: [PHP] First PHP job
On Tue, Jan 11, 2011 at 4:19 AM, Jay Blanchard wrote: > I am always looking for the $needle in the $haystack. > > Just sayin' > I often find it faster to hire a bunch of horses to eat the $haystack, leaving the $needle behind and easy to find. David
Re: [PHP] Command line PHP
On Tue, Jan 11, 2011 at 10:12 AM, tedd wrote: > My down time is playing XBOX Black Ops. It allows my mind to focus on > things that don't matter, much like a vacation, that's frees space > For me that's Left 4 Dead 2 as Captain Cujo. I think it's beneficial to cultivate skills in something that totally doesn't matter. Of course, in the event of an *actual* zombie apocalypse I'll be well prepared. :) David
Re: [PHP] First PHP job
On Tue, Jan 11, 2011 at 9:55 AM, Robert Cummings wrote: > My horse now has a perforated stomach and colon. Can I send you the > veterinarian's bill? > Who knew they made carrot-flavored $needles? David
Re: [PHP] Stripping carriage returns
On Tue, Jan 11, 2011 at 11:13 AM, Richard S. Crawford wrote: > $content = preg_replace("/[".chr(10)."|".chr(13)."]/","",$content) > This should be $content = preg_replace('/[\r\n]/','',$content) First, you can embed \r and \n directly in the regular expression as-is (not converted to chr(10) by PHP) by using single quotes. Second, you don't want the vertical bar inside []. That's only for (). David
Re: [PHP] HTML errors
On Wed, Jan 12, 2011 at 6:04 AM, David McGlone wrote: > Prounouncing words for a deaf person is often times difficult. > That makes perfect sense. Think about it, > spelling isn't about remembering how to spell the word, but how to > prounounce > it. Not so fast! While this argument can be made to many facets of spelling, changing a "y" to "ie" when adding an "s" to make a word plural is 100% rule memorization and 0% pronunciation. In the interest of full disclosure I must point out that I typed "pronounciation" and didn't notice until the browser corrected me. *smack* :) On Tue, Jan 11, 2011 at 8:48 PM, Daniel Brown wrote: > To override this, you must uncomment the following line in your system's > php.ini: > >;human = true > I tried this with PHP 5.3.2 on Ubuntu 10.04, but when I run any PHP script I get the following. Fatal error in php.ini line 184: Saying a thing doesn't make it so. What does this mean? David
Re: [PHP] Array Symbol Suggestion
On Thu, Jan 13, 2011 at 2:23 AM, Richard Quadling wrote: > The Hungarian Notation [1] was what I was taught all those years ago > when I learnt standard C programming. I learned it early on as well, and I never really liked it. Instead of $iFish I would prefer a more descriptive name such as $fishCount. Sure, it's a little longer to type, but it tells you what that number measures. In today's world of objects and loosely-typed languages, a descriptive variable name can be more important than a symbol or notation to hint at the type. As for arrays, I always name the variable plural. And if it maps keys to values instead of holding a list of items, I will typically name it $foosByBar, e.g. $customersById. From that name I *know* it's array already--no need for a prefix or special symbol. $oPlayer, $sName, $iWidth...what's the point? The context in which the variable is used can provide more meaning. If you stick to short functions/methods that do one specific thing, you'll be able to tell that $player is an object, $name is a string, and $width is an integer. I highly recommend the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. [1] It has a lot of great advice on keeping your code easy to understand, test, and maintain. David [1] http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
Re: [PHP] Array Symbol Suggestion
On Thu, Jan 13, 2011 at 10:07 AM, David Hutto wrote: > On Thu, Jan 13, 2011 at 12:59 PM, David Harkness > > I learned it early on as well, and I never really liked it. Instead of > > $iFish I would prefer a more descriptive name such as $fishCount. > > What info did you get on hook for the client? > The brain is so interesting. I have no idea where $iFish came from. I've never done an application even remotely related to fishing or the fishing industry. Not even a fish-based game. :) David
Re: [PHP] Closure and $this
On Wed, Jan 12, 2011 at 10:57 PM, Larry Garfield wrote: > I believe this is the relevant RFC: > > http://wiki.php.net/rfc/closures/object-extension > That was a good bedtime read last night, Larry. I prefer method A which is nearly identical to Java's inner classes where $this would remain tied to whatever it held when the closure was created and gain the object's scope. I do like the idea of being able to explicitly bind the closure to a new object as well. That's all well and good come PHP 5.4 or 6.0, but for now you are limited to holding a reference to $this without gaining its scope, i.e. you can only access public members. Also, you must assign $this to a new variable because you cannot pass $this in the use() clause. $that = $this; $closure = function(...) use ($that) { ... $that->property ... $that->method() ... } If you need access to a protected or private variable inside the closure, you can pass a reference to it inside use(). Once again you need to first assign the reference to a new variable and then pass that in to the closure. Important: you must use the & operator in the use() clause as well as when creating the reference. class ClosureFactory { private $count = 0; public function create() { $ref = &$this->count; return function() use (&$ref) { return ++$ref; }; } } $factory = new ClosureFactory(); $closure = $factory->create(); for ($i = 0; $i < 5; $i++) { echo $closure(); } Yields 12345 David
Re: [PHP] Class and interface location
What about creating your own docblock tag such as @plugin-interface? While it still requires each plugin to explicitly define the interface(s) it implements, it won't be in the class declaration. This would be very easy to nab for a tree of files using grep, removing the need to do any static analysis or parse PHP code. David