Categories
php

print_r in PHP-5.2.6 Doesn’t Print the Whole SimpleXML Object

There’s an interesting SimpleXML related bug in PHP 5.2.6 . print_r is unable to print all the contents of a SimpleXML object. The bug is reported on the php.net site.

The reproduction of the code is below:

Reproduce code:
---------------
<?php
$xmlstr=<<<EOXML
<?xml version='1.0' standalone='yes'?>l;
<products>
    <product order_id="0001"></product>
    <product order_id="0002">PHP book</product>
    <product order_id="0003">
        <name>PHP book</name>
    </product>
</products>
EOXML;

$xml=new SimpleXMLElement($xmlstr);
print_r($xml);
?>

Expected result:
----------------
@attributes array for second item as well

Actual result:
--------------
SimpleXMLElement Object
(
    [product] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [order_id] => 0001
                        )

                )

            [1] => PHP book
            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [order_id] => 0003
                        )

                    [name] => PHP book
                )

        )

)

[13 May 1:29pm UTC] felipe@php.net

The attribute can be accessed, however toString really doesn't show it.

print_r($xml->product[1]);

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [order_id] => 0002
        )

    [0] => PHP book
)

It’s been pretty interesting going through the code in php-5.2.6/ext/simplexml . A note in the README file provides a clue:

“Due to engine problems it is currently not possible to access a subelement by index 0: $object->property[0].”

Categories
TechBiz

#php on irc.he.net harbors a racist coder

16:43 < barce> @niklas` i’m writing a connect4 game, and noticed that when i traverse
diagonals acutely or gravely, the only diff between the functions is their
operators: “>=” or “<=". 16:43 < barce> “++” or “–”
16:44 < barce> so instead of if ($x < $limit) $x++; i want to define an operator before hand. 16:44 < barce> e.g. $op = “++”; if ($x < $limit) $x{$op}; 16:44 <+impl> so you save one line of code?
16:45 <@horros> Now why the hell would you want to do that?
16:45 <@feti> i’m successfully confused
16:45 < barce> ya. why not?
16:45 <+impl> because it’s stupid
16:45 < barce> why is it stupid?
16:45 <+impl> Because you would have to implement runtime operator resolution so that you
don’t have to have an else { } block
16:45 < barce> not being curious is stupid.
16:46 < barce> right.
16:46 < barce> that would be pretty hard to do.
16:46 <@horros> No, being curious is good.
16:46 < barce> so i’m asking if there’s a language like that.
16:46 <+impl> I’m sure you could nigger rig it in ruby

Please, come on down to #php irc.he.net and let this impl dude know what a blight to humanity he is.

Categories
How-To WebApps

How to Make Your Own PHP Extension… Quick and Dirty

This is a cheat sheet on how to extend PHP. I’m learning how to fix bugs in C within the PHP source code right now using what’s google-able, the #php chat room in irc.freenode.net and “Extending and Embedding PHP” by Sara Goleman.

Preliminaries: make sure you have the right tools for building php from source. Right now these tools are:

  • autoconf: 2.13
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • bison: 1.28, 1.35, 1.75, 2.0 or higher
  • flex: 2.5.4 (not higher)
  • re2c: 0.9.11+ (0.12.0+ for HEAD)
  • Get the latest php stable version. as of this blog posting it’s php-5.2.6
  • unpack the file using something like bunzip2 -c < php-5.2.6.tar.bz2 | tar xvf -
  • ./configure –prefix=/usr/local –enable-debug (I’m really old school and like to put my stuff in /usr/local . YMMV.)
  • make ; make install

If that worked now we’re ready to make a module. Feel free to substitute barce or BARCE in the code below with whatever you want the module name to be.

  • cd ext (if you type ls you’ll see the extensions that come with php.)
  • mkdir barce (I’m a narcissistic, buddhist, nihilist.)
  • create a config.m4 file with this code:
PHP_ARG_ENABLE(barce,
        [Whether to enable the "barce" extension],
        [  --enable-barce       Enable "barce" extension support])

if test $PHP_BARCE != "no"; then
        PHP_SUBST(BARCE_SHARED_LIBADD)
        PHP_NEW_EXTENSION(barce, barce.c, $ext_shared)
fi
  • then create a php_barce.h file:
#ifndef PHP_BARCE_H
/* Prevent double inclusion */
#define PHP_BARCE_H

/* Define extension properties */
#define PHP_BARCE_EXTNAME "barce"
#define PHP_BARCE_EXTVER "1.0"

/* Import configure options
 * when building outside of the 
 * PHP source tree */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/* Include PHP standard Header */
#include "php.h"
/*
 * define the entry point symbole
 * Zend will use when loading this module
 */
extern zend_module_entry barce_module_entry;
#define phpext_barce_ptr &barce_module_entry

#endif /* PHP_BARCE_H */

  • create a barce.c file with your functions that you are creating for PHP
#include "php_barce.h"

PHP_FUNCTION(barce_thinks_youre_cool)
{
        char *name;
        int name_len;

        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", 
                &name, &name_len) == FAILURE)
        {
                RETURN_NULL();
        }

        php_printf("Barce thinks you're cool, ");
        PHPWRITE(name, name_len);
        php_printf("!\n");
}


static function_entry php_barce_functions[] = {
        PHP_FE(barce_thinks_youre_cool, NULL)
        { NULL, NULL, NULL }
};

zend_module_entry barce_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
        STANDARD_MODULE_HEADER,
#endif
        PHP_BARCE_EXTNAME,
        php_barce_functions, /* Functions */
        NULL, /* MINIT */
        NULL, /* MSHUTDOWN */
        NULL, /* RINIT */
        NULL, /* RSHUTDOWN */
        NULL, /* MINFO */
#if ZEND_MODULE_API_NO >= 20010901
        PHP_BARCE_EXTVER,
#endif
        STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_BARCE
ZEND_GET_MODULE(barce)
#endif

Now let’s build this puppy.

  • phpize
  • ./configure –enable-barce
  • make
  • there should now be a modules directory. copy it to /usr/local/lib/php/modules/ .
  • edit php.ini and add two lines:
    • extension_dir = “/usr/local/lib/php/modules”
    • extension = “barce.so”

Let’s test and see if it worked:

php -r “barce_thinks_youre_cool(‘Put your name here’);”

Categories
TechBiz WebApps

Algorithms in PHP

I started coding algorithms in PHP in order to beef up my coding knowledge. It’s been an interesting exercise so far because when I coded algorithms in college it was great using C pointers.

Categories
How-To TechBiz WebApps

The Code of Successful Websites

Hypothesis:

Coding is a free market enterprise. Wild-west coding or coding anarchy is more profitable and more likely to encourage progress than following any coding methodology. (I.e. waterfall, agile, extreme, pair coding, etc.)

I. This is shown by the source code of the most successful companies. The only commonality they share is that their most popular product feature was born of a non-methodological hack. It is only after the initial phase of success that a company brings order to the code.

II. The code that brings a company its first success is un-readable and un-maintainble.

III. Coding profitably is a result of breaking the rules and letting the market rather than the development process decide. Web analytics is vital.

IV. The consistency condition that demands coders code according to a design pattern or for the sake of maintainability is unreasonable because it either preserves an unprofitable coding methodology or obscures money making logic in the guise of readable code.

V. There is no coding method or technology however absurd or ancient that cannot be profitable. (My Space running on Cold Fusion w/SQL Servers as a back end.)

VI. There exists no code base that is capable of generating profit that is 100% in harmony with a given coding methodology. Many code bases are constituted by older technologies and older ways of making money; therefore a clash between methodologies is a sign of being wise and sensitive to changing markets.

Categories
TechBiz

Part II of Hegel, Coding and Managers: Your boss and Hegel think it’s life or death but it’s not

DISCLAIMER: This article in no way is based on previous or current employers, and/or clients past or present.

I have great admiration for Joel Spoelsky who runs Fog Creek Software, because frankly, his advice has helped me in my career when I’ve run into tough situations. He has helped me thrive. In his, “Fire and Motion” article, he made it really clear to me what productivity means as a developer.

He’s been seduced by a certain Hegelism that most managers feel deep down to the core, and he expresses it really clearly when he talks about finding great developers.

In the last piece, I talked about how coders work under the false notion that coding will somehow make them better managers. Hegel expressed this in the Phenomenology of Spirit where the slave somehow through her work becomes free. Marx would later exploit this romantic delusion of Hegel’s and we are still cleaning up the mess from this lost cause. Mind you, I am in favor of returning Che Guevara’s stolen rolex to Cuba.

In this piece, there’s a specific prejudice that managers have that you can see in Hegel’s Master-Slave Dialectic. The one who becomes the master does so because she risked all:

[I]t is only through staking one’s life that freedom is won… The individual who has not risked his life may well be recognized as a person, but he has not attained to the truth of this recognition as an independent self-consciousness. (s. 187)

Having risked all, the master is entitled to the enjoyment of the products of the slave and is the measure of the slave’s worth.

This sort of scrutiny and prejudice towards the slave can seen in the coder’s interview process.

Basically, you want a coder who can:
1) Do Smart Things
2) Do those Smart Things to Completion, i.e. Get Stuff Done

I’m not disagreeing with that at all, but let’s take the straw man of an example where Joel tells us not to hire the smart guy who can’t get things done:

‘People who are Smart but don’t Get Things Done often have PhDs and work in big companies where nobody listens to them because they are completely impractical. They would rather mull over something academic about a problem rather than ship on time. These kind of people can be identified because they love to point out the theoretical similarity between two widely divergent concepts. For example, they will say, “Spreadsheets are really just a special case of programming language,” and then go off for a week and write a thrilling, brilliant whitepaper about the theoretical computational linguistic attributes of a spreadsheet as a programming language. Smart, but not useful. The other way to identify these people is that they have a tendency to show up at your office, coffee mug in hand, and try to start a long conversation about the relative merits of Java introspection vs. COM type libraries, on the day you are trying to ship a beta.’

There are two criticisms here against the manager:
1) The manager was pretty dumb in hiring a guy who is an academic. Theory is the work of the academic. In their minds, they have already gotten stuff done.
2) The manager labors under a false sense of urgency, the sort of urgency that makes the master so oppressive to the slave in Hegel’s version of the story.
3) A combination of both.

You might be calling bullshit right now, but I know of a multi-million dollar company that would never call someone out on being too geeky like Joel did or brandish academic like a dirty word. That company is 37signals.

They did a unique experiment with a 4 day work week, and it’s turned out great!

Basically, they argue that urgency is poisonous:

One thing I’ve come to realize is that urgency is overrated. In fact, I’ve come to believe urgency is poisonous. Urgency may get things done a few days sooner, but what does it cost in morale? Few things burn morale like urgency. Urgency is acidic.

Emergency is the only urgency. Almost anything else can wait a few days. It’s OK. There are exceptions (a trade show, a conference), but those are rare.

When a few days extra turns into a few weeks extra then there’s a problem, but what really has to be done by Friday that can’t wait for Monday or Tuesday? If your deliveries are that critical to the hour or day, maybe you’re setting up false priorities and dangerous expectations.

If you’re a just-in-time provider of industry parts then precise deadlines and deliveries may be required, but in the software industry urgency is self-imposed and morale-busting. If stress is a weed, urgency is the seed. Don’t plant it if you can help it.

Categories
Uncategorized

Part I of Hegel, Coding and Managers: The Blindness of Coders

This is a real rant from a techie who works for a company in San Mateo:

Recently our CTO (who also is a word class fool) promoted a guy to the position of lead product architect. I would like to mention that the product whose architect he has appointed has never contributed any work worth mentioning.

If you take a look at the only feature he has managed to make and he was the only resource assigned on that feature so I suppose he had all the options to take his decision and come up with a word class implementation, comprises of one file only. Yeah just one file and this one file contains tons of classes which have methods reaching 1K lines.

So you can imagine where the focus is. It clearly shows that this guy has never programmed under a good leadership. He is so worried about getting this fact disclosed that he managed to convince the CTO to not allow anyone to even see his code let alone suggest improvements. That’s one of the reasons I call the CTO a fool too 🙂

God knows what more is to come from this word class duo.

— source an anonymous lead engineer in San Mateo

The first thing that struck me is this. Why is this guy telling me this? Why isn’t he telling the CTO? One of the mythologies that Hegel pedals is the idea that the status quo is a result of a life and death struggle with the result being a great inequality. The time for talk has passed long ago, and what we have is this:

[O]ne is the independent consciousness whose essential nature is to be for itself, the other is the dependent consciousness whose essential nature is simply to live or to be for another. The former is the master, the other is the slave. (Phenomenology of Spirit, s. 189)

Hegel’s way out for the slave is the work that the slave does on things. Hegel characterizes work as “desire held in check, fleetingness staved off… It is precisely in his work wherein he seemed to have only an alienated existence that he acquires a mind of his own… having a ‘mind of one’s own’ is self-will, a freedom.” (s. 195 – 196) Through service and discipline the slave makes herself stronger. The slave working on her work sees herself as essential and the master as unessential. This sets the stage for the slaves escape to freedom or possible domination of the master. In Marx, this is when the workers rise and take over all ownership of the means of production. The unessential, i.e. the owners, are done away with or made into workers themselves. Nobody is any longer master nor slave.

On the PHP Meetup list, I asked the question, “Have there ever been coders who have coded their way to freedom?”

I was given two examples, neither of which answered the question, and show that yes, a lot of coders do falsely believe that coding leads to freedom.

1) John Gilmore, a founder of the EFF which is an organization I support with donations.

2) Richard Stallman.

I’d say neither is free because although Gilmore made a fortune at Sun, coding didn’t lead to that freedom as a necessary condition. There are coders as good as Gilmore who don’t have that cash. The fact that EFF had to be founded points to the un-freedom of coders.

As far as Stallman goes, I admire his work. I use a lot of GNU software. However, I don’t have enough fingers to count the companies that close source GNU software and try and re-sell it as their own.

So, as you can see coding isn’t enough. Yet coders feel their coding makes them qualified to call CTOs fools. Ya, I can see that putting 1000s of lines of code into one file can be dumb. I can also see that promoting a bad coder is a bad idea. Good coding allows you to see this, but this guy in San Mateo has bought into the idea that he can’t talk to this CTO, that somehow the solution to the problem is technical, i.e. better code.

If you’re a coder, my advice to you is that the time to talk isn’t over. It hasn’t been settled in a Hegelian life and death struggle where the inequalities are currently fixed. If you talk, you still have a chance. Email your gripes now, and you might even be surprised.

In my next post, I talk about the prejudices that managers have towards coders.

Categories
TechBiz

Hegel, Coding and Managers

DISCLAIMER: The comments here in no way reflect the work situation of my current employer, Dogster, or current clients, or any of my previous employers or clients.

I’ll share two secrets with you: Coders dislike their managers. Managers dislike their coders.

According to the 2007 Goldman Sachs survey of employee job satisfaction, most workers want out of their jobs, and tech work ranked in the top 5 of jobs with the least satisfaction.

I am concerned with coders and managers who don’t have the work situation I have, and I think that there are certain mythologies that coders and managers have that prevent them from having job satisfaction.

I think Hegel is the instigator of these mythologies.

Hegel

I found these mythologies that coders and managers base their gripes on within what Hegel calls the Master-Slave Dialectic.

I encourage you to read the wikipedia entries.

I will follow up with two posts.

Part I: I talk about how coders use mythologies that prevent them from seeing their work situation for what it is. Although these mythologies originate in Hegel, they pervade media, e.g. Dilbert.

Part II: What do managers say about coders? To get to this information, you have to go behind the scenes. It isn’t at all pretty the sorts of prejudices managers have towards their coders, and if they could free themselves from these, they would enjoy management much more.

Categories
Uncategorized

Update your To Do List from Your Cell and Share Flowcharts with Everyone

To make flowcharts Web 2.0 style check out Gliffy.com.

Looking for a To Do list that works off-line as well as on-line? Do you also need to send your To Do items via SMS from your cell phone?

I love Remember The Milk just for this sort of thing.

Categories
Uncategorized

Sun Breaks MySQL’s Source Install

I was supposed to go to Medjool to meet up with the Zappos crew, but instead I ended up helping a pal with a MySQL database upgrade problem with version 5.1.24-rc.

The upgrade was a cluster fuck!

These steps for upgrading MySQL have served me well for the past 9 years.

tar cvf backup_data.tar /usr/local/mysql/var/*
gzip backup_data.tar
cd /usr/local/src/mysql-5.1.24-rc
./configure --prefix=/usr/local/mysql --with-mysqld-user=mysql --with-ssl
make
make install
scripts/mysql_install_db

Then I’d just run ‘/usr/local/libexec/mysqld –user=mysql &’ and I’d be on my merry way to happily computing on the web.

But now wiith version 5.1.24-rc of MySQL, I’d have to ask what the heck are they doing at Sun to MySQL?

When I started the server, I noticed that the state files were running in /var . Big fail there, since the prefix is defined as /usr/local/mysql .

Also, I noticed that when I ran scripts/mysql_install_db there were more path errors:

FATAL ERROR: Could not find /fill_help_tables.sql

Then the biggest source of fail occured when I ran this:

/usr/local/libexec/mysqld –print-defaults

/usr/local/mysql/libexec/mysqld would have been started with the following arguments:

--port=3306 --socket=/tmp/mysql.sock --skip-locking --key_buffer=16M 
--max_allowed_packet=1M --table_cache=64 --sort_buffer_size=512K 
--net_buffer_length=8K --read_buffer_size=256K 
--read_rnd_buffer_size=512K --myisam_sort_buffer_size=8M 
--log-bin=mysql-bin --server-id=1 --user=mysql 
--pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock
--port=3306 --basedir=/usr --datadir=/var/lib/mysql --tmpdir=/tmp
--language=/usr/share/mysql/english --skip-external-locking --bind-address=127.0.0.1
--key_buffer=16M --max_allowed_packet=16M --thread_stack=128K --thread_cache_size=8
--query_cache_limit=1M --query_cache_size=16M --expire_logs_days=10 --max_binlog_size=100M
--skip-bdb 

Once again, path errors, and –skip-bdb is an option that doesn’t even exist for mysqld!!!!!!

Here was my fix for the scripts’ install:

./scripts/mysql_install_db --no-defaults --port=3306 --socket=/tmp/mysql.sock \ 
--skip-locking --key_buffer=16M --max_allowed_packet=1M --table_cache=64 \
--sort_buffer_size=512K --net_buffer_length=8K --read_buffer_size=256K  \
--read_rnd_buffer_size=512K --myisam_sort_buffer_size=8M --log-bin=mysql-bin \ 
--server-id=1 --user=mysql --pid-file=/var/run/mysqld/mysqld.pid \
--socket=/var/run/mysqld/mysqld.sock \
 --port=3306 --basedir=/usr/local/mysql --datadir=/usr/local/mysql/var \
--tmpdir=/tmp --language=/usr/local/mysql/share/mysql/english --skip-external-locking \
--bind-address=127.0.0.1 --key_buffer=16M --max_allowed_packet=16M \
--thread_stack=128K --thread_cache_size=8 --query_cache_limit=1M \
--query_cache_size=16M --expire_logs_days=10 --max_binlog_size=100M

Here’s my fix for how the server must start from now on:

/usr/local/mysql/bin/mysqld_safe --no-defaults --port=3306  \
--socket=/tmp/mysql.sock --skip-locking --key_buffer=16M  \
--max_allowed_packet=1M --table_cache=64 --sort_buffer_size=512K  \
--net_buffer_length=8K --read_buffer_size=256K  \
--read_rnd_buffer_size=512K --myisam_sort_buffer_size=8M  \
--log-bin=mysql-bin --server-id=1 --user=mysql  \
--pid-file=/var/run/mysqld/mysqld.pid  \
--socket=/var/run/mysqld/mysqld.sock --port=3306  \
--basedir=/usr/local/mysql --datadir=/usr/local/mysql/var  \
--tmpdir=/tmp --language=/usr/local/mysql/share/mysql/english  \
--skip-external-locking --bind-address=127.0.0.1 --key_buffer=16M  \
--max_allowed_packet=16M --thread_stack=128K --thread_cache_size=8  \
--query_cache_limit=1M --query_cache_size=16M  \
--expire_logs_days=10 --max_binlog_size=100M &

All that just to start a server, so now, I’m totally telling my friends to use PostgreSQL instead. Sure it’s slower and doesn’t scale as much by a factor of 4 compared to MySQL, but hey, maybe it’s time for something new.