Feb 15

PHP ScrewsSometimes, you want to run PHP with Tomcat. Why? Well, you may have a legacy product, for instance, that will require servlets for many more years. Or you may be using this gigantic Java program and are only interested in adding a tiny PHP piece on the side.

There are many guides showing how to do this available, but they become outdated almost as soon as they are published. So, it’s my turn to write a short-lived guide, this time for PHP 5.2.5 :)
Note thas this post relies greatly on information found here. Too bad even that guide got old so fast!

  1. Go to http://www.php.net/downloads.php and download the current version. I am going to do the setup on a Windows machine here, so I can simply download the binaries. On *nix, you will need to compile PHP. I know I will have to, anyway…
  2. You also need to download the corresponding PECL modules.
  3. Let’s assume that your current Tomcat install can be found in c:\Tomcat5\. Create a c:\Tomcat5\php\ directory and unzip the PHP zip file in it.
  4. Rename php.ini-dist, in c:\Tomcat5\php\, to php.ini
  5. Extract php5servlet.dll from the PECL zip file to c:\Tomcat5\php\
  6. Create a directory under c:\Tomcat5\webapps\; in our case: phptest
  7. In c:\Tomcat5\webapps\phptest\, create a subdirectory: WEB-INF
  8. In c:\Tomcat5\webapps\phptest\WEB-INF\, create web.xml with the following content:
    ini
    1. <?xml version="1.0" encoding="ISO-8859-1"?>
    2. <!DOCTYPE web-app PUBLIC
    3.   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    4.   "http://java.sun.com/dtd/web-app_2_3.dtd">
    5. <web-app>
    6.         <servlet>
    7.                 <servlet-name>php</servlet-name>
    8.                 <servlet-class>net.php.servlet</servlet-class>
    9.         </servlet>
    10.         <servlet>
    11.                 <servlet-name>php-formatter</servlet-name>
    12.                 <servlet-class>net.php.formatter</servlet-class>
    13.         </servlet>
    14.         <servlet-mapping>
    15.                 <servlet-name>php</servlet-name>
    16.                 <url-pattern>*.php</url-pattern>
    17.         </servlet-mapping>
    18.         <servlet-mapping>
    19.                 <servlet-name>php-formatter</servlet-name>
    20.                 <url-pattern>*.phps</url-pattern>
    21.         </servlet-mapping>
    22. </web-app>
  9. Extract/unjar (using jar xvf or WinZip) php5srvlt.jar under c:\Tomcat5\php\tmp\
  10. Modify both c:\Tomcat5\php\tmp\net\reflect.properties and c:\Tomcat5\php\tmp\net\servlet.properties, replacing
    ini
    1. library=phpsrvlt

    with

    ini
    1. library=php5servlet

    and save.

  11. Jar the content of c:\Tomcat5\php\tmp\ into a new version of php5srvlt.jar
  12. Move php5srvlt.jar to c:\Tomcat5\common\lib\
  13. Copy c:\Tomcat5\php\php5servlet.dll and c:\Tomcat5\php\php5ts.dll to c:\windows\system32\
  14. Create a test page in c:\Tomcat5\webapps\phptest\test.php with this contents:
    PHP
    1. <?php phpinfo(); ?>
  15. Start Tomcat and go to http://localhost:8080/phptest/test.php

It should work. If it doesn’t, you can always post the stack trace here.

Sphere: Related Content

Feb 08

JSONJSON, or JavaScript Object Notation, is fairly popular.
This is just my modest take on a ‘PHP Object Notation’ implementation.
Note that it is meant to follow how your mind works rather than being syntactically correct; therefore, associative arrays are used in a loose manner where you have to worry about associative syntax as little as possible.
Basically, type away until your object is fully described.

Here is a notation sample:

PHP
  1.         ‘root level’ => array(
  2.                 ’sublevel 1′ => array(
  3.                         ’sublevel 2′ => ’sublevel 3′,
  4.                 ),
  5.         )
  6. );

.
This syntax can then be used the same way JSON is used, using eval. Here is how and you will immediately notice how the eval() syntax has to differ from the JavaScript one:

PHP
  1. $remote_str = <<<EOB
  2.     array(
  3.         ‘root level’ => array(
  4.                 ’sublevel 1′ => array(
  5.                         ’sublevel 2′ => ’sublevel 3′,
  6.                 ),
  7.         )
  8. );
  9. EOB;
  10. // …
  11. eval(‘$local_str=’.$remote_str.‘;’);

.
Feels a bit clumsy. Fortunately, starting with PHP4, if you are not too sad about introducing a statement in your remote string, you can rewrite it like this:

PHP
  1. $remote_str = <<<EOB
  2. return array(
  3.         ‘root level’ => array(
  4.                 ’sublevel 1′ => array(
  5.                         ’sublevel 2′ => ’sublevel 3′,
  6.                 ),
  7.         )
  8. );
  9. EOB;
  10. // …
  11. $local_str = eval($remote_str);

.
Better, isn’t it?

In this last listing, you will find the very simple code I wrote to traverse the object. Note that I invoke a callback for every element, otherwise this code would not be very helpful.

Note that this is just a concept for something I needed to throw together quickly therefore there are some limitations; for instance, you cannot have numeric keys since in this context their “keyness” is ignored and even feared.

PHP
  1. <?php
  2. function traverse_tree($callback, $curlevel, $curdepth, $uid)
  3. {
  4.         $depthstr = ‘——————————————————————————’;
  5.         $padding = substr($depthstr, 0, $curdepth);
  6.         if(!is_array($curlevel))
  7.         {
  8.                 $callback($curlevel, $padding, $uid);
  9.                 return;
  10.         }
  11.         foreach($curlevel as $level=>$children)
  12.         {
  13.                 if(!is_numeric($level))
  14.                 {
  15.                         $my_uid = $callback($level, $padding, $uid);
  16.                         traverse_tree($callback, $children, $curdepth + 2, $my_uid);
  17.                 }
  18.                 else
  19.                 {
  20.                         $callback($children, $padding, $uid);
  21.                 }
  22.         }
  23. }
  24.  
  25. function do_something($name, $padding, $uid)
  26. {
  27.         $iid = 0; // Bogus value
  28.         print $padding.$name." ($iid)\n";
  29.         return $iid;
  30. }
  31.  
  32. // ———————————————————–
  33. // Here we go
  34. // ———————————————————–
  35. if(count($argv) != 2)
  36.         die("\nSyntax: ".$PHP_SELF." ‘root_node_name’\n\n");
  37. $rootnodename = &$argv[1];
  38.  
  39. $INS = array(
  40.         $rootnodename => array(
  41.                 ‘Bikes’ => array(
  42.                         ‘Yamaha’ => ‘Fz’,
  43.                         ‘Honda’,
  44.                         ‘Norton’
  45.                         ),
  46.                 ‘Trikes’,
  47.                 ‘Cars’ => array(
  48.                         ‘Chevrolet’ => array(
  49.                                 ‘Corvette’ => array(‘Z06′, ‘Convertible’, ‘Coupe’),
  50.                                 ‘Camaro’,
  51.                                 ‘Jimmy’
  52.                                 ),
  53.                         ‘Ford’ => array(
  54.                                 ‘Mustang’ => array(‘GT’, ‘Premium’, ‘Shelby’, ‘Other’=>‘Roush’),
  55.                                 ‘Explorer’,
  56.                                 ‘Crown Victoria’
  57.                                 ),
  58.                         ‘Chrysler’ => array(
  59.                                 ‘Dodge’ => ‘Charger’,
  60.                                 ‘300X’,
  61.                                 ‘Le Baron’
  62.                                 ),
  63.                         )
  64.         )
  65. );
  66.  
  67. traverse_tree(do_something, $INS, 0, 1);
  68.  
  69. print "DONE\n\n";
  70. ?>

.
Invoke with:

  1. php my_php_script.php "Vehicles"

.
“What is this $iid variable?” you may ask.
You will notice that this piece of code is particularly convenient if you want to add a whole tree structure to your database. Say the you are using MySQL and want to create categories and sub-categories, using the column ‘pid’ as a category’s parent id. You would rewrite do_something:

PHP
  1. function do_something($name, $padding, $uid)
  2. {
  3.         mysql_query("INSERT INTO my_cat_table(pid, title) VALUES({$uid}, ‘{$name}’)");
  4.         $iid = mysql_insert_id();
  5.         print $padding.$name." ($iid)\n";
  6.         return $iid;
  7. }

Voila!

Sphere: Related Content

Feb 04

FlickosoftHere it is in all its glory. From Microsoft’s Press Page.
If you do a search for “microsoft yahoo” on Flickr, you will find a lot of interesting images; no idea whether this represents the opinion of only a few vocal people or if indeed Flickr users are, as a group, quite nonplussed.
A suggestion: if people are this much peeved, why not organize a massive exodus from Flickr, reducing its nominal value to zero? Now that would be grassroots…

Board of Directors
Yahoo! Inc.
701 First Avenue
Sunnyvale, CA 94089
Attention: Roy Bostock, Chairman
Attention: Jerry Yang, Chief Executive Officer
Dear Members of the Board:
I am writing on behalf of the Board of Directors of Microsoft to make a proposal for a business combination of Microsoft and Yahoo!. Under our proposal, Microsoft would acquire all of the outstanding shares of Yahoo! common stock for per share consideration of $31 based on Microsoft’s closing share price on January 31, 2008, payable in the form of $31 in cash or 0.9509 of a share of Microsoft common stock. Microsoft would provide each Yahoo! shareholder with the ability to choose whether to receive the consideration in cash or Microsoft common stock, subject to pro-ration so that in the aggregate one-half of the Yahoo! common shares will be exchanged for shares of Microsoft common stock and one-half of the Yahoo! common shares will be converted into the right to receive cash. Our proposal is not subject to any financing condition.
Our proposal represents a 62% premium above the closing price of Yahoo! common stock of $19.18 on January 31, 2008. The implied premium for the operating assets of the company clearly is considerably greater when adjusted for the minority, non-controlled assets and cash. By whatever financial measure you use - EBITDA, free cash flow, operating cash flow, net income, or analyst target prices - this proposal represents a compelling value realization event for your shareholders.
We believe that Microsoft common stock represents a very attractive investment opportunity for Yahoo!’s shareholders. Microsoft has generated revenue growth of 15%, earnings growth of 26%, and a return on equity of 35% on average for the last three years. Microsoft’s share price has generated shareholder returns of 8% during the last one year period and 28% during the last three year period, significantly outperforming the S&P 500. It is our view that Microsoft has significant potential upside given the continued solid growth in our core businesses, the recent launch of Windows Vista, and other strategic initiatives.
Microsoft’s consistent belief has been that the combination of Microsoft and Yahoo! clearly represents the best way to deliver maximum value to our respective shareholders, as well as create a more efficient and competitive company that would provide greater value and service to our customers. In late 2006 and early 2007, we jointly explored a broad range of ways in which our two companies might work together. These discussions were based on a vision that the online businesses of Microsoft and Yahoo! should be aligned in some way to create a more effective competitor in the online marketplace. We discussed a number of alternatives ranging from commercial partnerships to a merger proposal, which you rejected. While a commercial partnership may have made sense at one time, Microsoft believes that the only alternative now is the combination of Microsoft and Yahoo! that we are proposing.
In February 2007, I received a letter from your Chairman indicating the view of the Yahoo! Board that “now is not the right time from the perspective of our shareholders to enter into discussions regarding an acquisition transaction.” According to that letter, the principal reason for this view was the Yahoo! Board’s confidence in the “potential upside” if management successfully executed on a reformulated strategy based on certain operational initiatives, such as Project Panama, and a significant organizational realignment. A year has gone by, and the competitive situation has not improved.
While online advertising growth continues, there are significant benefits of scale in advertising platform economics, in capital costs for search index build-out, and in research and development, making this a time of industry consolidation and convergence. Today, the market is increasingly dominated by one player who is consolidating its dominance through acquisition. Together, Microsoft and Yahoo! can offer a credible alternative for consumers, advertisers, and publishers. Synergies of this combination fall into four areas:
Scale economics: This combination enables synergies related to scale economics of the advertising platform where today there is only one competitor at scale. This includes synergies across both search and non-search related advertising that will strengthen the value proposition to both advertisers and publishers. Additionally, the combination allows us to consolidate capital spending.
Expanded R&D capacity: The combined talent of our engineering resources can be focused on R&D priorities such as a single search index and single advertising platform. Together we can unleash new levels of innovation, delivering enhanced user experiences, breakthroughs in search, and new advertising platform capabilities. Many of these breakthroughs are a function of an engineering scale that today neither of our companies has on its own.
Operational efficiencies: Eliminating redundant infrastructure and duplicative operating costs will improve the financial performance of the combined entity.
Emerging user experiences: Our combined ability to focus engineering resources that drive innovation in emerging scenarios such as video, mobile services, online commerce, social media, and social platforms is greatly enhanced.
We would value the opportunity to further discuss with you how to optimize the integration of our respective businesses to create a leading global technology company with exceptional display and search advertising capabilities. You should also be aware that we intend to offer significant retention packages to your engineers, key leaders and employees across all disciplines.
We have dedicated considerable time and resources to an analysis of a potential transaction and are confident that the combination will receive all necessary regulatory approvals. We look forward to discussing this with you, and both our internal legal team and outside counsel are available to meet with your counsel at their earliest convenience.
Our proposal is subject to the negotiation of a definitive merger agreement and our having the opportunity to conduct certain limited and confirmatory due diligence. In addition, because a portion of the aggregate merger consideration would consist of Microsoft common stock, we would provide Yahoo! the opportunity to conduct appropriate limited due diligence with respect to Microsoft. We are prepared to deliver a draft merger agreement to you and begin discussions immediately.
In light of the significance of this proposal to your shareholders and ours, as well as the potential for selective disclosures, our intention is to publicly release the text of this letter tomorrow morning.
Due to the importance of these discussions and the value represented by our proposal, we expect the Yahoo! Board to engage in a full review of our proposal. My leadership team and I would be happy to make ourselves available to meet with you and your Board at your earliest convenience. Depending on the nature of your response, Microsoft reserves the right to pursue all necessary steps to ensure that Yahoo!’s shareholders are provided with the opportunity to realize the value inherent in our proposal.
We believe this proposal represents a unique opportunity to create significant value for Yahoo!’s shareholders and employees, and the combined company will be better positioned to provide an enhanced value proposition to users and advertisers. We hope that you and your Board share our enthusiasm, and we look forward to a prompt and favorable reply.
Sincerely yours,
/s/ Steven A. Ballmer
Steven A. Ballmer
Chief Executive Officer
Microsoft Corporation

Sphere: Related Content

Feb 03

References…almost :)
Another update:
After reading some of the comments to this entry, I googled ‘pass-by-reference’ and discovered that the semantic aspect of what the phrase means has been the topic of many topics along time with funny titles such as “More on Java- pass by reference, but not really” or more seriously “Parameter passing in Java - by reference or by value?” or what I consider the clearest, best articulated article on the topic: Java is Pass-By-Value, Dammit!
(end of update)

Next day update:
OK, thanks go to the first 3 commenters: when venturing into the semantic field, this entry is inaccurate. I should have used this title actually: Java Does Pass-A-Reference because it actually passes the reference’s value.
What does this mean? Well, Java passes a reference to the original object; however it passes a copy of its original reference.
After making this clear, you can keep reading because the point I am making - which is that the language’s behaviour, similar to C’s behaviour, should not come as a surprise - still stands and I am glad to be prompted to clarify it since it makes easier for the reader to grasp why modifying the argument does not change the reference :)
(end of update)

It is simple: either a function/method argument is an object, in which case a reference is passed, or it is not and the argument’s value is passed.
I just read this blog entry that somehow made it to DZone’s home page: Java Does Not Pass-By-Reference.
Well, it is unfortunate. The author makes the case that Java does not pass a reference to an object in a way that would allow him to manipulate said reference.
Of course, this is correct but I find the examples provided somewhat misguided since references themselves are not here to be manipulated but to let you manipulate the object (or, since he mentions C, the memory space) they reference.

Of course, to stay in tune with his C analogy, I should mention that you can modify the reference’s value itself if you use a pointer to a pointer in your function/method signature. For instance, in C, to modify a char* reference, this would look like this:

void myfunction(char **my_double_dereference)
{
    (*mydoublereference) = (char*)malloc(sizeof(char*)*my_size);
}

Now, our original memory space was not modified in the process. However, its reference was lost and replaced with a new reference to a new memory allocation.

C was originally written to be a better macro-assembler. With each new language generation, we are getting further away from the original intent by abstracting the architecture of the machine your program is compiled for. Java is one of the “recent” (Ahem! It’s all relative) languages that tried to free developers from having to worry about pointers. Of course, it quickly became obvious that if, on the one hand, it was easy to write a new program in Java, memory management was not going away and it is very difficult to write clean code if you do not understand its principles. (Note to some commenters: I never wrote that Java does away with pointers)

Note that if you wish to modify references in Java, you can still do that, but you have to be a bit more creative and wrap your reference in another object: this is, for example, how weak references work as you are actually passing a reference to the weak reference’s constructor. Not the object referenced.

Using the same model, let’s rewrite Adam’s Figure 4:

public static void main(String[] args) {
    StringBuffer sb1 = new StringBuffer("Hello");
    StringBufferWrapper wrapper = new StringBufferWrapper(sb1);
    doSomething(wrapper);
    sb1 = wrapper.reference;   

    // what gets printed?
    if (sb1 == null) {
        System.out.println("sb1 is null");
    } else {
        System.out.println("sb1 is not null");
    }
}   

public void doSomething(StringBufferWrapper sb2) {
    sb2.reference = null;
}

I hope I didn’t introduce any mistake in my code, it’s a tad late but you get the idea.

As usual, let me know if this elicits any question on this topic or weak references or what not…
Cheers!

Sphere: Related Content