Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Windows Azure, PHP, ...

NAVIGATION - SEARCH

Linuxwochen Austria

As part of my global domination plans, I this week visited Vienna, Austria for a session at Linuxwochen around PHP on Windows.

PHP on Windows

Abstract: “Ever wanted to get started with PHP development on Windows? This session covers the basics of running PHP on the Windows platform and will help getting your development environment ready.”

Thanks for being in this session! I know it is a controversial one on a Linux event :-)

TechDays 2010 Portugal slides and demo code

First of all: thank you for attending the sessions Kevin Dockx and I gave at TechDays 2010 Portugal! A wonder we made it there with all the ash clouds and volcanic interference based in Iceland.

Just Another Wordpress Weblog, But More Cloudy

Abstract: “While working together with Microsoft on the Windows Azure SDK for PHP, we found that we needed an popular example application hosted on Microsoft’s Windows Azure. Wordpress was an obvious choice, but not an obvious task. Learn more about Windows Azure, the PHP SDK that we developed, SQL Azure and about the problems we faced porting an existing PHP application to Windows Azure.”

I can not disclose demo code at this time, sorry. Here’s a list of good resources to get you started though:

PHP and Silverlight

Abstract: “So you have an existing PHP application and would like to spice it up with a rich and attractive front-end. Next to Adobe Flex, you can also choose Silverlight as a solution. This session shows you around in Silverlight and shows that PHP and Silverlight can go together easily.”

Demo code: PHP and Silverlight - DevDays.zip (1.00 mb) (based on Silverlight 2, bug Kevin for a recent version :-))

Book review: Zend Framework 1.8 Web Application Development

Zend Framework 1.8 Web Application Development My book shelf is starting to look a lot like the warehouse of Packt Publishing: I’ve received yet another book from them. Different from all previous reviews I did: this one is a PHP book, titled “Zend Framework 1.8 Web Application Development” by Keith Pope.

A chapter overview:

  • Chapter 1: Creating a Basic MVC Application
  • Chapter 2: The Zend Framework MVC Architecture
  • Chapter 3: Storefront Basic Setup
  • Chapter 4: Storefront Models (great chapter!)
  • Chapter 5: Implementing the Catalog
  • Chapter 6: Implementing User Accounts
  • Chapter 7: The Shopping Cart
  • Chapter 8: Authentication and Authorization
  • Chapter 9: The Administration Area
  • Chapter 10: Storefront Roundup
  • Chapter 11: Storefront Optimization
  • Chapter 12: Testing the Storefront

Let’s also state the obvious: Zend Framework evolves much faster than publishers. The framework is now at 1.9.6, while the book covers 1.8.0. Do not let this stop you from reading this book! Let me explain why…

  1. The book covers all concepts and components in the Zend Framework in a full-blown application that is built up from scratch.
  2. Next to that, Keith Pope focuses a lot on the application design, using interfaces, unit testing, mocking, dependency injection, … Want to learn a lot about good application design? Then this is the number one reason to read this book!

These 2 points actually summarize the whole book. Great read, great content and a must-read for everyone who is not completely sure about his application design skills. Congratulations, Keith!

Simple API for Cloud Application Services

Zend, in co-operation with IBM, Microsoft, Rackspace, GoGrid and other cloud leaders, today have released their Simple API for Cloud Application Services project. The Simple Cloud API project empowers developers to use one interface to interact with the cloud services offered by different vendors. These vendors are all contributing to this open source project, making sure the Simple Cloud API “fits like a glove” on top of their service.

Zend Cloud adapters will be available for services such as:

  • File storage services, including Windows Azure blobs, Rackspace Cloud Files, Nirvanix Storage Delivery Network and Amazon S3
  • Document Storage services, including Windows Azure tables and Amazon SimpleDB
  • Simple queue services, including Amazon SQS and Windows Azure queues

Note that the Simple Cloud API is focused on providing a simple and re-usable interface across different cloud services. This implicates that specific features a service offers will not be available using the Simple Cloud API.

Here’s a quick code sample for the Simple Cloud API. Let’s upload some data and list the items in a Windows Azure Blob Storage container using the Simple Cloud API:

[code:c#]

require_once('Zend/Cloud/Storage/WindowsAzure.php');

// Create an instance
$storage = new Zend_Cloud_Storage_WindowsAzure(
'zendtest',
array(
  'host' => 'blob.core.windows.net',
  'accountname' => 'xxxxxx',
  'accountkey' => 'yyyyyy'
));

// Create some data and upload it
$item1 = new Zend_Cloud_Storage_Item('Hello World!', array('creator' => 'Maarten'));
$storage->storeItem($item1, 'data/item.txt');

// Now download it!
$item2 = $storage->fetchItem('data/item.txt', array('returntype' => 2));
var_dump($item2);

// List items
var_dump(
$storage->listItems()
);

[/code]

It’s quite fun to be a part of this kind of things: I started working for Microsoft on the Windows Azure SDK for PHP, we contributed the same codebase to Zend Framework, and now I’m building the Windows Azure implementations for the Simple Cloud API.

The full press release can be found at the Simple Cloud API website.

Query the cloud with PHP (PHPLinq and Windows Azure)

PHPLinq Architecture I’m pleased to announce PHPLinq currently supports basic querying of Windows Azure Table Storage. PHPLinq is a class library for PHP, based on the idea of Microsoft’s LINQ technology. LINQ is short for language integrated query, a component in the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

Next to PHPLinq querying arrays, XML and objects, which was already supported, PHPLinq now enables you to query Windows Azure Table Storage in the same manner as you would query a list of employees, simply by passing PHPLinq a Table Storage client and table name as storage hint in the in() method:

[code:c#]

$result = from('$employee')->in( array($storageClient, 'employees', 'AzureEmployee') )
            ->where('$employee => $employee->Name == "Maarten"')
            ->select('$employee');

[/code]

The Windows Azure Table Storage layer is provided by Microsoft’s PHP SDK for Windows Azure and leveraged by PHPLinq to enable querying “the cloud”.

kick it on DotNetKicks.com

PHP SDK for Windows Azure - Milestone 2 release

WindowsAzure I’m proud to announce our second milestone for the PHP SDK for Windows Azure project that Microsoft and RealDolmen started back in May. Next to our regular releases on CodePlex, we’ll also be shipping a Zend Framework version of the PHP SDK for Windows Azure. Announcements on this will be made later.

The current milestone is focused on Windows Azure Table Storage, enabling you to use all features this service offers from any PHP application, be it hosted in-premise or on Windows Azure.

Get it while it’s hot: PHP SDK for Windows Azure CTP2 - PHPAzure CTP2 (0.2.0)

Detailed API documentation is provided in the download package, while more descriptive guidance is available on the project site.

Working with Azure Table Storage from PHP

Let’s provide a small example on the new Table Storage support in the PHP SDK for Windows Azure. The first thing to do when you have a clean storage account on the Azure platform is to create a new table:

[code:c#]

/** Microsoft_Azure_Storage_Table */
require_once 'Microsoft/Azure/Storage/Table.php';

$storageClient = new Microsoft_Azure_Storage_Table('table.core.windows.net', 'myaccount', 'myauthkey');
$storageClient->createTable('mynewtable');

[/code]

Easy, no? Note that we did not provide any schema information here as you would do in a regular database. Windows Azure Table Storage can actually contain entities with different properties in the same table. You can work with an enforced schema, but this will be client-side. More info on that matter is available here.

Now let’s add a person to the “mynewtable” in the cloud:

[code:c#]

$person = new Microsoft_Azure_Storage_DynamicTableEntity('partition1', 'row1');
$person->Name = "Maarten";
$person->Age  = 25;

$storageClient->insertEntity('mynewtable', $person);

[/code]

Again, no rocket science. The Microsoft_Azure_Storage_DynamicTableEntity class used provides fluent access to entities in Table Storage. More info on this class is available here.

Now let’s add a property to this $person instance and merge it into Table Storage:

[code:c#]

$person->Blog = "www.maartenballiauw.be";
$storageClient->mergeEntity('mynewtable', $person);

[/code]

Wow! We just added a Blog property to this object! I could have also used updateEnity for this, but that one would have overwritten eventual changes that were made to my $person in the meantime.

Now for some querying. Let’s retrieve all entities in “mynewtable” that have an Age of 25:

[code:c#]

$entities = $storageClient->storageClient->retrieveEntities(
    'mynewtable',
    $storageClient->select()
                  ->from($tableName)
                  ->where('Age eq ?', 25)
);

foreach ($entities as $entity)
{
    echo 'Name: ' . $entity->Name . "\n";
}

[/code]

I guess this al looks quite straightforward. The fluent query building API provides a syntax similar to how you would build a query in SQL.

Another nice feature of the PHP SDK for Windows Azure is support for batch transactions. Here’s an example of how to work with transactions on Table Storage:

[code:c#]

// Start batch
$batch = $storageClient->startBatch();

// Insert entities in batch
$entities = array( ...... );
foreach ($entities as $entity)
{
    $storageClient->insertEntity('mynewtable', $entity);
}

// Commit
$batch->commit();

[/code]

The batch will fail as a whole if one insert, update, delete, ... does not work out, just like with a transaction on a regular relational database like MySQL or SQL Server.

If you're interested in cloud computing and WIndows Azure, and want to keep using PHP, make sure to get the latest version of the PHP SDK for Windows Azure to leverage all functionality that is available in the cloud. Here's the link: PHP SDK for Windows Azure CTP2 - PHPAzure CTP2 (0.2.0)

PHP and Silverlight - DevDays session

I just returned from The Hague where Kevin and I delivered a session on PHP and Silverlight. As promised, we are putting our slides and demos online. Download the demo code from here: PHP and Silverlight - DevDays.zip (1.00 mb)

Abstract:

"So you have an existing PHP application and would like to spice it up with a rich and attractive front-end. Next to Adobe Flex, you can also choose Silverlight as a solution. This session shows you around in Silverlight and shows that PHP and Silverlight can go together easily."

We really enjoyed DevDays and want to thank everyone who was there (and was in our session while beer drinking seemed more appropriate that time of day).

Announcing PHP SDK for Windows Azure

As part of Microsoft’s commitment to Interoperability, a new open source project has just been released on CodePlex: PHP SDK for Windows Azure, bridging PHP developers to Windows Azure. PHPAzure is an open source project to provide software development kit for Windows Azure and Windows Azure Storage – Blobs, Tables & Queues. I’m pleased that Microsoft has chosen RealDolmen and me to work on the PHP SDK for Windows Azure.

logomicrosoft logorealdolmen

Windows Azure provides an open, standards-based and interoperable environment with support for multiple internet protocols.  This helps reduce the cost of running a mixed IT environment.  Azure building block services use XML, REST and SOAP standards so they can be called from other platforms and programming languages.  Developers can create their own services and applications that conform to internet standards. Next to the new PHP SDK for Windows Azure, Microsoft also shipped Java and Ruby SDK for .NET Services demonstrating how heterogeneous languages and frameworks could take advantage of interoperable Identity Service (Access Control) & Service Bus using SOAP and REST-based frameworks.

  • Overview
    • Enables PHP developers to take advantage of the Microsoft Cloud Services Platform  – Windows Azure
    • Provides consistent programming model for Windows Azure Storage (Blobs, Tables & Queues)
  • Features
    • PHP classes for Windows Azure Blobs, Tables & Queues (for CRUD operations)
    • Helper Classes for HTTP transport, AuthN/AuthZ, REST & Error Management
    • Manageability, Instrumentation & Logging support

The logical architecture of PHP SDK for Windows Azure is as follows: it provides access to Windows Azure's storage, computation and management interfaces by abstracting the REST/XML interface Windows Azure provides into a simple PHP API.

logical_architecture

An application built using PHP SDK for Windows Azure can access Windows Azure's features, no matter if it is hosted on the Windows Azure platform or on an in-premise web server.

deployment_scenario

You can contribute, provide feature requests & test your own enhancements to the toolkit by joining the user forum.

kick it on DotNetKicks.com

Accessing Windows Azure Blob Storage from PHP

Pfew! A week of Microsoft TechDays here in Belgium with lots of talks on new Microsoft stuff, Azure included. You may know I already experimented with Windows Azure and ASP.NET MVC. Earlier this week, I thought of doing the same with Windows Azure and PHP...

What the ...?

imageAt Microsoft PDC 2008, the Azure Services Platform was announced in the opening keynote. Azure is the name for Microsoft’s Software + Services platform, an operating system in the cloud providing services for hosting, management, scalable storage with support for simple blobs, tables, and queues, as well as a management infrastructure for provisioning and geo-distribution of cloud-based services, and a development platform for the Azure Services layer.

You can currently download the Windows Azure SDK from www.azure.com and play with it on your local computer. Make sure to sign-up at the Azure site: you might get lucky and receive a key to test the real thing.

And what does PHP have to do with this?

As a reader of my blog, this should not be a question. I'm on the thin line between the Microsoft development environment (.NET) and PHP development environment, and I really like bridging the two together (think PHPExcel, PHPLinq). And cheap, distributed hosting of data (be it file or databases) is always interesting to use, especially in web applications where you may store anything your users upload. I have created a Zend Framework Proposal for this, let's hope this blog post ends as a contribution to the Zend Framework.

Show me the good stuff!

Will do! Currently, I have only implemented Azure blob storage in PHP, so that's what the following code snippets will be using. Enough blahblah now, here's how you connect with Azure:

[code:c#]

$storage = new Zend_Azure_Storage_Blob();

[/code]

This actually sets up a connection with the local Azure storage service from the Windows Azure SDK. You can, however, also pass in an account name and shared key from the real, cloud hosted Azure, too. Next: I want to create a storage container. A storage container is a logical group in which I can store any data. Let's name the container "azuretest":

[code:c#]

$storage->createContainer('azuretest');

[/code]

Easy? Yup! Azure now has created some space on their distributed storage for my files to be dumped in. Speaking of which: let's upload a file!

[code:c#]

$storage->putBlob('azuretest', 'images/WindowsAzure.gif', './WindowsAzure.gif');

[/code]

There we go. I've uploaded my local WindowsAzure.gif file to the azuretest container and named the file "images/WindowsAzure.gif'". Don't be confused: it is NOT stored in the images/ folder (there's no such thing on Azure), this is really the full filename. But don't worry, you can mimic a regular filesystem with folders, for example by retrieving all files that are prefixed with "images/":

[code:c#]

$storage->listBlobs('azuretest', '/', 'images/');

[/code]

Piece of cake!

I wanna play!

Sure, who doesn't? Here's a preview of the classes I've been creating: Zend_Azure_CTP.zip (11.51 kb)

Now let's hope my Zend Framework Proposal gets accepted so this can be a part of the Zend Framework. In the meantime, I'll continue with this and also implement Azure table storage: cheap, distributed database features in the cloud.

kick it on DotNetKicks.com

PHPLinq 0.4.0 released on CodePlex!

PHPLinq I’m pleased to announce that PHPLinq 0.4.0 has been released on CodePlex. PHPLinq is currently one year old, and I decided to add a huge step in functionality for the 0.4.0 release. This blog post will focus on the current status of PHPLinq and what it is capable of doing for you in a PHP project.

 

What is PHPLinq?

PHPLinq is a class library for PHP, based on the idea of Microsoft’s LINQ technology. LINQ is short for language integrated query, a component in the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

Using PHPLinq, the same functionality is created in PHP. Since regular LINQ applies to enumerators, SQL, datasets, XML, ..., I decided PHPLinq should provide the same infrastructure. Here’s an example PHPLinq query, which retrieves all names with a length less than 5 from an array of strings:

[code:c#]

// Create data source
$names = array("John", "Peter", "Joe", "Patrick", "Donald", "Eric");

$result = from('$name')->in($names)
            ->where('$name => strlen($name) < 5')
            ->select('$name');

[/code]

Notice the in()-function? This is basically a clue for PHPLinq to determine how t query data. In this case, PHPLinq will work with a string array, but is perfectly possible to hint PHPLinq with a database table, for example. I’ll show you more on that later in this post.

PHPLinq components

This functionality is achieved by the fact that each PHPLinq query is initiated by the PHPLinq_Initiator class. Each PHPLinq_ILinqProvider implementation registers itself with this initiator class, which then determines the correct provider to use. This virtually means that you can write unlimited providers, each for a different data type!

PHPLinq architecture

What can I do with PHPLinq?

Basically, PHPLinq is all about querying data. No matter if it’s an array, XML tree or a database table, PHPLinq should be able to figure out what to do witht the data, without you being required to write complex foreach loops and stuff like that.

Querying data from an array

Let’s have a look at an example. The following array will be a dataset which we’ll be working with. It is a list of Employee objects.

[code:c#]

// Employee data source
$employees = array(
    new Employee(1, 1, 5, 'Maarten', 'maarten@example.com', 24),
    new Employee(2, 1, 5, 'Paul', 'paul@example.com', 30),
    new Employee(3, 2, 5, 'Bill', 'bill.a@example.com', 29),
    new Employee(4, 3, 5, 'Bill', 'bill.g@example.com', 28),
    new Employee(5, 2, 0, 'Xavier', 'xavier@example.com', 40)
);

[/code]

I would like to have the name and e-mail address of employees named “Bill”. Here’s a PHPLinq query:

[code:c#]

$result = from('$employee')->in($employees)
            ->where('$employee => substr($employee->Name, 0, 4) == "Bill"')
            ->select('new {
                    "Name" => $employee->Name,
                    "Email" => $employee->Email
                  }');

[/code]

Wow! New things here! What’s this $employee => … thing? What’s this new { … } thing? The first is a lambda expression. This is actualy an anonymous PHP function we are creating, accepting a parameter $employee. This function returns a boolean (true/false), based on the employee’s name. The new { … } thing is an anonymous class constructor. What we are doing here is defining a new class on-the-fly, with properties Name and Email, based on data from the original $employee.

Here’s the output of the above query:

[code:c#]

Array
(
    [0] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.a@example.com
        )
    [1] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.g@example.com
        )
)

[/code]

How cool is that! Things are getting a lot cooler when we use PHPLinq together with the Zend Framework’s Zend_Db_Table

Querying data from a database

PHPLinq has a second PHPLinq_ILinqProvider built in. This provider makes use of the Zend Framework Zend_Db_Table class to provide querying capabilities. First things first: let’s create a database table.

[code:c#]

CREATE TABLE employees (
    Id                INTEGER NOT NULL PRIMARY KEY,
    DepartmentId    INTEGER,
    ManagerId        INTEGER,
    Name            VARCHAR(100),
    Email            VARCHAR(200),
    Age                INTEGER
);

[/code]

We’ll be using this table in a Zend_Db_Table class:

[code:c#]

// EmployeeTable class
class EmployeeTable extends Zend_Db_Table {
    protected $_name = 'employees'; // table name
    protected $_primary = 'Id';
}
$employeeTable = new EmployeeTable(array('db' => $db));
$employeeTable->setRowClass('Employee');

[/code]

Allright, what happened here? We’ve created a database table, and told Zend_Db_Table to look in the employees table for data, and map these to the Employee class we created before. The Zend_Db_Table employee table will be accessible trough the $employeesTable variable.

Ok, let’s issue a query:

[code:c#]

$result = from('$employee')->in($employeesTable)
            ->where('$employee => substr($employee->Name, 0, 4) == "Bill"')
            ->select('new {
                    "Name" => $employee->Name,
                    "Email" => $employee->Email
                  }');

[/code]

Here’s the output of the above query:

[code:c#]

Array
(
    [0] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.a@example.com
        )
    [1] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.g@example.com
        )
)

[/code]

Did you notice this query is actually the same as we used before? Except for the $employeesTable now being used instead of $employees this query is identical! The only thing that is different, is how PHPLinq handles the query internally. Using the array of objects, PHPLinq will simply loop the array and search for correct values. Using Zend_Db_Table, PHPLinq actually builds a SQL query which is executed directly on the database server, delegating performance and execution to the database engine.

We can have a look at the generated query by setting an option on PHPLinq, which will tell PHPLinq to pass the generated query to PHP’s print function.

[code:c#]

PHPLinq_LinqToZendDb::setQueryCallback('print');

[/code]

Let’s run the previous query again. The console will now also display the generated SQL statement:

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (SUBSTR('$employee'."Name",  0,  4)  =  "Bill")

[/code]

Cool! Are you kidding me?!? PHPLinq just knew that the PHP code in my where clause translates to the above SQL statement! It’s even cooler than this: PHPLinq also knows about different databases. The above example will translate to another query on a different database engine. For that, let’s look at another example. Here’s the PHPLinq query:

[code:c#]

$result = from('$employee')->in($employeeTable)
            ->where('$employee => trim($employee->Name) == "Bill"')
            ->select('$employee->Name');

[/code]

The generated SQL statement in SQLite:

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (TRIM('$employee'."Name")  =  "Bill")

[/code]

The generated SQL statement in Microsoft SQL Server (only knows LTRIM() and RTRIM(), not TRIM()):

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (LTRIM(RTRIM('$employee'."Name"))  =  "Bill")

[/code]

I don't know about you, but I think this is very useful (and COOL!)

Querying data from an XML source

Here’s another short example, just to be complete. Let's fetch all posts on my blog's RSS feed, order them by publication date (descending), and select an anonymous type containing title and author. Here's how:

[code:c#]

$rssFeed = simplexml_load_string(file_get_contents('http://blog.maartenballiauw.be/syndication.axd'));
$result = from('$item')->in($rssFeed->xpath('//channel/item'))
            ->orderByDescending('$item => strtotime((string)$item->pubDate)')
            ->take(2)
            ->select('new {
                            "Title" => (string)$item->title,
                            "Author" => (string)$item->author
                      }');

[/code]

Where to go now?

There’s lots of other features in PHPLinq which I covered partially in previous blog posts (this one and this one). For full examples, download PHPLinq from www.phplinq.net and see for yourself.

By the way, PHPExcel (another project of mine) and PHPLinq seem to be listed in Smashing Magazine's Top 50 list of extremely useful PHP tools. Thanks for this recognition!