KBD

Keith Devens .com

Friday, March 19, 2010 Flag waving
The Lord is my shepherd; I shall not want. – David (Psalm 23)

Tag: PHP

Parents:

Daily link icon Thursday, July 24, 2008

  1. Second p0st: PHP hackery: quick and dirty anonymous objects. Eew.

       (0) Tags: [PHP]

Daily link icon Saturday, July 19, 2008

  1. FirePHP - Firebug Extension for AJAX Development (via).

       (0) Tags: [Firefox, PHP]

Daily link icon Monday, September 24, 2007

  1. 7 reasons I switched back to PHP after 2 years on Rails - O'Reilly Ruby (via). The main reason I'd hope to switch to Rails is not for Rails itself, but to be able to use Ruby. If only PHP used Ruby Smiley frowning

       (0) Tags: [PHP, Ruby, Ruby on Rails]

Daily link icon Wednesday, November 8, 2006

  1. PHP: JSON Functions - Manual. Ooh, JSON is now built into PHP. Rock on. (Via Simon)

       (0) Tags: [Json, PHP]

Daily link icon Thursday, July 27, 2006

Dumb substring behavior in C# (and Java)

Substring in C# (and Java) throw an exception if you take a substring and give it a length (or a starting position) that puts you after the end of the string. That's basically to ensure that you always get a string that's exactly the length you want? Rather than just being able to take a substring and not having to worry about it, you have to include code like the following around every single substring you ever take:

if (str.Length > 30){
    str = str.Substring(0, 30);
}

Typically when you take a substring you want to ensure that your string is no longer than a certain number of characters. I can't think of a situation that would it a good idea for the language to enforce that you can't get a string that's less than the maximum length you want instead of exactly the length you want.

On the other hand, most of the dynamic languages (PPPR) let you substring off the end of the string without worrying about it.

Daily link icon Saturday, March 18, 2006

  1. ASP.NET 2.0 Training Center: Cross Training for Web Developers:

    This section of the ASP.NET 2.0 Training Center helps the PHP developer learn more about PHP, and also add to their skillset by mastering ASP.NET 2.0. In the coming weeks, you'll learn how to get up to speed with ASP.NET 2.0, and you'll find details about interoperability between PHP and ASP.NET 2.0.

    To help you, you'll also find a series of webcasts specifically created, from the ground up, by world-class experts and presenters to teach ASP.NET to PHP developers.

    Started reading the first article on the page and it's excellent so far.

       (0) Tags: [ASP.NET, PHP]

Daily link icon Sunday, March 5, 2006

  1. John Lim: ADOdb Implementation of Active Record: cloning Zend_Db_DataObject:

    The Zend Framework Preview edition is out. I had look this morning at Zend_Db_DataObject, which is an implementation of the Active Record pattern. After reading the tutorial, decided to implement something similar for ADOdb. After a couple of hours coding, I had an implementation that works with both PHP4 and PHP5, and provides a superset of the functionality described in the above link.

       (0) Tags: [PHP]

Daily link icon Thursday, March 2, 2006

  1. James Manning's blog : error CS1501: No overload for method 'Base' takes '0' arguments. Why don't more languages come with 'unified constructors' like Python (and even PHP, now) does? Wouldn't that fix the problem?

       (0) Tags: [C#, OOP, PHP, Python]

Daily link icon Saturday, February 25, 2006

Ajaxian » Troubles with Asynchronous Ajax Requests and PHP Sessions

Ajaxian » Troubles with Asynchronous Ajax Requests and PHP Sessions. Links to Marc Wandschneider's post explaining why you need to think about about possible race conditions with session data when using Ajax. Via Keith Gaughan, who posts some good comments on the Ajaxian thread about causes and possible solutions.

In short, server-side technologies like PHP don't let you lock access to your session across requests. So, you can A. try to do some complicated locking of your own on the server. B. store the critical session data in a MySQL RAM table (or some other equivalent) which AFAIK will handle the locking for you (of course, you're still not safe in this case unless you're careful). C. give the client knowledge of what changes the session state on a server that could lead to a race condition, and make sure those requests are serialized (i.e. get a response from the server before sending the next request).

Update: Harry Fuecks has a follow-up article on this.

Daily link icon Wednesday, February 22, 2006

  1. Harry Fuecks: A pro-PHP Rant. Would have blogged this last night (I did blog some links from the article) but I fell asleep Smiley

    Heh, Matt comments: "Hear hear. Sometimes I feel guilty about how easy it has been to scale WordPress.com from 1 to 110,000 blogs in just a few months."

       (0) Tags: [PHP]

Daily link icon Tuesday, February 21, 2006

PHP's 'create_function' function

PHP's create_function function is so cumbersome to use that I'm creating shortcuts for the most common cases. Very often all you want to do is a map and return a particular field out of an associative array. So:

<?php
function mapfield($key$func=null){
    return 
create_function('$a',"return $func(\$a['$key']);");
}
?>

Used as in:

<?php
function tags_join($tags){
    
#given an array of tags give the canonical space separated listing
    
return join(' ',array_unique(array_map(mapfield('Name'), $tags)));
}
?>

Daily link icon Sunday, February 19, 2006

FireBug, and interactive consoles

So yesterday, for the first time in years, I started coding a little Javascript, so I finally had a reason to install and play with FireBug. It's great. By far the most useful feature to me so far is the interactive javascript console. You can say document.getElementById("foo") and it'll give you a debug list of all the properties for that element. And you can execute any Javascript and it'll show you the results.

It really shows the value of interactive consoles. In fact, that was the second interactive console I'd made use of for the day for a language that doesn't usually have one. I finished creating a fairly tricky API for my tagging system, and I wanted to test it all. So I whipped up my own web-based interactive console for PHP where I could type in code and have it be evaluated and see the output. I was able to run down my entire API pretty quickly and both knock out some minor errors, and convince myself that the code was probably correct. With the console I wrote I was able to run through my tests much faster than I'd have been able to any other way.

A console is so important to me that I feel kind of naked when I'm working in a language that doesn't have one. In particular, I really miss it when I'm working with Perl, especially given its baroque syntax and all the CPAN you're inevitably testing out.

Daily link icon Friday, February 17, 2006

  1. FuzzyBlog » Blog Archive » Responding to Ian on PHP:

    I tend to reuse code from other PHP developers incredibly selectively. So I’ll pull in damn near anything from Simon or from Keith or Matt and a few other sources...

    Aww, shucks.

       (0) Tags: [Personal, PHP, Programming]

Daily link icon Thursday, November 24, 2005

PHP sucks yet again

Via Jeff, just found these PHP Developers' Meeting minutes on PHP 6. Call-time pass-by-reference was deprecated for no reason somewhere along the line. Now they're un-deprecating it, changing it back from an E_WARNING (they claim it's E_NOTICE, but it's not) to just E_STRICT (though they're also turning E_STRICT on by default):

The first issue that we raised was changing the E_NOTICE error for call-time-pass-by-reference to an E_ERROR, or simply throwing a parse error. We argued over this case and we decided to change this E_NOTICE to an E_STRICT instead as it was argued that there is nothing wrong with doing a call-time pass by reference.

Argh! I vented my frutration about this feature being deprecated since it broke some of PHP's built-in functionality. Now it's just "Sorry, there really was no reason for us to deprecate that feature. Our bad".

On the bright side, it looks like they're removing magic quotes and register globals.

Also, the PHP people couldn't agree on how to fix a sore spot in the language if you develop with notices on. You commonly have to do things like the following:

<?php
$foo 
= isset($_REQUEST['foo']) ? $_REQUEST['foo'] : NULL;
?>

so that you don't get an error if $_REQUEST['foo'] doesn't exist. Obviously that's really cumbersome to do over and over again. They proposed adding an ifsetor function that does essentially the following:

<?php
function ifsetor($var$default){
    return isset(
$var) ? $var $default;
}
?>

But note the special casing in their example:

<?php
$foo 
ifsetor($_GET['foo'], 42);
?>

That's not allowed if $_GET['foo'] doesn't already exist; if I call my version of ifsetor I get a NOTICE error. So, they'd add a special case in the language (just like they already have with isset) to make it appear as if $_GET['foo'] returns NULL if it's not defined. But if that was the case it would defeat the whole purpose of the feature anyway!

However, they decided against ifsetor and instead are adding a syntax extension that lets you elide the middle value for the ternary operator for the common case as shown above, which would allow:

<?php
$foo 
$_REQUEST['foo'] ?: NULL;
?>

Which really isn't bad at all. Only:

Instead of implementing ifsetor() we remove the requirement for the "middle" parameter to the ?: operator. The middle parameter then defaults to the first one. If the first parameter is not set, then we will still throw an E_NOTICE.

So, again the feature becomes useless for the common case I've been talking about. However, they've provided the following for me:

<?php
$foo 
input_filter_get(GET'foo'FL_INT) ?: 42;
?>

Great.

FYI, I have a few convenience functions just for these common cases:

<?php
function g(&$var$key$default NULL){ #make it easy to develop with notices on
    
return isset($var[$key]) ? $var[$key] : $default;
}
function 
r($key){ return g($_REQUEST$key); }
?>

g optionally does some more than that, but that's the base case.

Now, this I'm very happy about. They're getting rid of the `{}` indexing for strings (which they admit was a hack to simplify their parser) and allowing slicing notation like Python does. That's excellent. They k'd on named parameters, however.

Note: any emphasis in any quote above is my own.

Daily link icon Monday, March 7, 2005

PHP 5 bug in array_walk?

The following code works differently in PHP 4 and PHP 5.

<?php
array_walk
($tagmarkscreate_function('&$a',
'if(isset($a[\'tag_array\'])){
   array_walk($a[\'tag_array\'],\'resolveTitle\');
   sortTags($a[\'tag_array\']);
}'
));
?>

Here's resolveTitle and sortTags:

<?php
function resolveTitle(&$tag){ #used for callbacks
    
$tag['title'] = formatTitle($tag);
}
function 
sortTags(&$tags){
    
usort($tags'compareTags');
}
function 
compareTags($a,$b){
    
#accounts for if the titles are the same, and then sorts by tag
    
return $a['title'] == $b['title'] ?
        
strcmp($a['tag'],$b['tag']) :
        
strnatcasecmp($a['title'],$b['title']);
}
?>

(Some code reformatted to wrap.) In PHP 5, the code only handles the first instance of a 'tag_array', whereas on 4 it does what it should. AFAICT this code isn't hitting any known problem areas of PHP 5 (such as object references), so, without doing more analysis, the only thing I can blame the difference on is a bug in PHP 5. Maybe the array_walk nesting does it?

I'm sticking this here largely because I'm going to change the code to make it work in PHP 5, and I want a record of it. I don't have time now to A) go through the PHP CVS looking for changes that would cause this B) play with this to isolate what's broken. Anyone have any idea what's making this code break?

Daily link icon Sunday, December 26, 2004

Function composition in PHP

For the hell of it:

<?php
#function composition in PHP
function compose(){
    
$args array_filter(func_get_args(),'is_callable');
    
$call join('(',$args).'($a'.str_repeat(')',count($args));
    return 
create_function('$a',"return $call;");
}
function 
bold($text){ return "<b>$text</b>"; }
function 
italic($text){ return "<i>$text</i>"; }
$func compose('bold','italic');
echo 
$func('text'); #prints "<b><i>text</i></b>"
?>

Daily link icon Sunday, October 17, 2004

How to do a line count of all included files in PHP

For future reference, here's some quick-and-dirty code to get a line count of all included files during a PHP execution:

<?php
    $files 
get_included_files();
    
usort($files,create_function('$a,$b','return strcmp(basename($a),basename($b));'));
    
$t 0;
    foreach(
$files as $f){
        
$c count(file($f));
        
$t+=$c;
        echo 
'| '.basename($f).' | '.$c." |\n";
    }
    echo 
$t;
?>

(By the way, the reason I used the vertical bars in the output is because that's the markup for tables on my weblog. See the following post for some of the output.)

Daily link icon Wednesday, June 30, 2004

Friendster switches to PHP

Friendster switched to PHP from their previous Java solution and became much faster. You can debate the cause of it (which lots of people are doing), but I'd recommend checking out Jeff Moore's large roundup of all related news and commentary. What seems to be coming out of this is that people are becoming aware of the merits of PHP's "shared nothing" architecture.

Update: George has a cranky, snarky answer to why PHP scales that should be very much worth your time to read. You may also want to check out The J2EE guy still doesn't get PHP, by Harry Fuecks.

Update: More from Sterling and John.

Update: Jeff Moore rounds up some more commentary and asks, "Scalability - YAGNI?"

Update: More summary here.

Daily link icon Tuesday, March 9, 2004

Boo MySQL

I'm normalizing some database tables more than I was hoping to get away with. I would have gotten away with it too, if it wasn't for you meddling kids... er, if I didn't need the ability to rename what I was planning to make a key.

Because MySQL doesn't support subqueries (if there was ever a case of worse-is-better, it's PHP and MySQL), the following very simple query:

UPDATE Bookmark_Keywords SET Bookmark_Keyword_Id = (
   SELECT Bookmark_Keyword_Id
   FROM Bookmark_Keyword_Info
   WHERE Bookmark_Keyword_Name = Bookmark_Keyword
)

is going to require that I write procedural code to update the table. Bust.

Update: For future reference, here's the code I had to write:

<?php
$sql 
'SELECT DISTINCT Bookmark_Keyword_Info.Bookmark_Keyword_Id id, Bookmark_Keyword_Name name
   FROM Bookmark_Keyword_Info
   INNER JOIN Bookmark_Keywords ON(Bookmark_Keyword_Name = Bookmark_Keyword)
   ORDER BY Bookmark_Keyword_Name'
//reformatted to fit layout
$rs_id mysql_query($sql$conn) or die("Couldn't select your keywords: ".mysql_error());
while(
$row mysql_fetch_assoc($rs_id)){
    
$sql "UPDATE Bookmark_Keywords
        SET Bookmark_Keyword_Id = $row[id]
        WHERE Bookmark_Keyword = '$row[name]'"
// reformatted to fit layout
    
print_r($row);
    echo 
'<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    
print_r($sql);
    
mysql_query($sql$conn) or die("Couldn't update your table: ".mysql_error());
    echo 
'<br>';
}
?>

Any formatting in there (print_r, echo), etc., was for me to see that the right thing was going to happen before I uncommented the mysql_query line. And of course, this is just "one-off" code... for instance, I didn't addslashes() on $row[name] because I knew none of my names had slashes or quotes in them.

Daily link icon Wednesday, August 13, 2003

I hate PHP

I hate PHP... just hate it. Hate it hate it hate it.

The newest thing I've been dealing with is the idiotic call-time pass-by-reference deprecation. I've never heard the reasoning for the deprecation, and as far as I can tell, there isn't any. I should start keeping a list of all the things that become impossible without it...

  • You can't have a default argument in a function that's passed by reference: function ($foo, &$bar = NULL){} doesn't work, although it will in PHP 5. Great, make alternatives available before you deprecate features, assholes.
  • Want to append a reference to an array using array_unshift, array_push, etc.? array_unshift($array, &$value) is no good. The only solution for array_unshift is to create new arrays and manually shuffle everything around.
  • Want to allow a callback to be called using call_user_func and have its arguments passed by reference? You're out of luck again. The only solution is to wrap a reference to your argument in an array and pass that... and your callback functions have to be rewritten to take arrays.
  • Finally, the worst example, which has caused me to waste literally hours trying to fix it is this: I've been removing call-time pass-by-reference from my XML-RPC library, because it's deprecated and people keep getting error messages when using my library (which isn't good). So, I tried to remove call-time pass-by-reference stuff a long time ago when I started working on version 3. So now I started working on the XML parsing part of it, which happens to use xml_set_object. Check out the documentation for that... it uses this line: "xml_set_object($this->parser, &$this);" Which, of course... **IS DEPRECATED**

I'm so mad my head's going to explode... I've been trying very hard to avoid littering this post with four letter words. What this last example shows is that xml_set_object is completely useless without being able to pass an object reference in there, since typically you'll store instance data representing your XML data in that object, and if you don't pass $this by reference you'll wind up with copies all over the place, which is what was happening to me. I think the solution to this is to pass array(&$this, "callback") to xml_set_element_handler, so we'll see.

The last example should work in PHP 5 as well, since objects will be passed by reference and not by value (which was another damn huge design mistake in the first place). But they deprecated a feature, which causes everyone to get big ugly error messages (not even NOTICEs, but WARNINGs) under the default install, without providing any workarounds or replacements.

PHP is a horrid language that I never want to have to do any development with ever again. Unfortunately, there are really no alternatives available that are widely deployed on shared hosts.

Daily link icon Saturday, December 8, 2001

You know what? PHP's "magic quotes" was definitely a bad idea. I'm convinced of it. Rather than it making life easier, to write good PHP code you have to wind up putting stuff like this everywhere:

<?php
if(!get_magic_quotes_gpc()){
    
$string addslashes($string);
}
?>

or if you want to print something:

<?php
if(get_magic_quotes_gpc()){
    echo 
stripslashes($string);
}
?>

The only time you need it is when you're entering stuff into a database. Also, I think if you do prepared statements ("insert into table (field1, field2) values(?, ?)"), when you execute the statement with the correct values it'll automatically add slashes for you.

In summary, magic quotes doesn't allow you to stop worrying about whether your strings are quoted or not, and it makes you do extra work to make sure your code behaves right regardless of what your configuration is.

March 2010
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 2 posts

Recent comments XML

I hate ASP.NET

I hate ASP... I was doing wonders​with PHP, then suddenly one of my​clients...

Johnies: Mar 17, 6:14am

Quantum physics and free will

I knew you were going to say that....

Tom Massey: Mar 15, 9:26pm

Generated in about 0.249s.

(Used 10 db queries)