Silverlight for PHP Developers

A Microsoft browser plug-in might seem an odd target for the PHP developer, more used to working with open source platforms such as Linux, Apache and the MySQL database server. However there is much about Microsoft Silverlight that makes it a good match to such technologies. For a start, it is a free download and there are versions that run not only on Microsoft Windows XP and Vista but also on Intel-based Apple Macs running OS X 10. It is designed to work not only with Microsoft Internet Explorer but with all major Web browsers, and Microsoft is taking particular care to ensure compatibility with Firefox and Safari. There is even a version for Linux called Moonlight which is being developed as part of the open source Mono Project.

Silverlight is a powerful tool for creating Internet applications that go considerably beyond the capabilities of standard HTML and CSS. It supports a wide range of visual effects and has more than 30 user interface controls built-in, including not only buttons, list boxes and sliders but also a data grid and a calendar. It can display PNG and JPEG image files, and play back WMV, WMA and MP3 media with support for 720p HDTV display modes. Silverlight 1.0 was released in April 2007. The current version is Silverlight 2.0 (originally referred to as Silverlight 1.1) which is fully compatible with the original while offering many enhancements.

Inside a Silverlight application
You define the application that you want Silverlight to present using XAML (eXtensible Application Markup Language). This is based on the XML specification and was designed by Microsoft for initialising structured values and objects. The following XAML document declares a Canvas object containing a TextBlock, which is a lightweight element for displaying text:

Code example. Click link below to donwload actual text.

Download complete code example

The visual elements that make up a Silverlight application need to be placed within a container object, and this provides a reference in which they can be positioned. In our example we are using a Canvas object measuring 300 by 100 pixels as the container and we have set its Background property so that it displays in a light blue color. Into this we have placed a single TextBlock object which will display the traditional ‘Hello World!’ text string in a Verdana font 30 pixels in size and 10 pixels below and to the right of the top-left corner of the Canvas object. Note the dot syntax that we have employed to reference properties of the Canvas object.

Actually displaying a Silverlight application within an HTML page need involve little more than a standard Object tag. At its simplest, the following renders our example within a browser:

Code example. Click link below to donwload actual text.

Download complete code example

Here we have defined a space 300 pixels wide and 100 pixels wide in which to place the Silverlight plug-in, as defined by its MIME type. We have also defined a data attribute for the plug-in. In practice this is usually ignored but it can boost performance with some browsers (and note that the trailing comma is necessary as the attribute takes two parameters, the second having a ‘null’ value in this case). Finally, in the event that the client does not have Silverlight 2.0 installed, the anchor element displays a ‘Get Silverlight’ image from the Microsoft Web site which is linked to the page from which the user can download and install the plug-in.

The Silverlight plug-in takes a number of parameters but in this context the most important is ‘source’ which tells the plug-in where to find the application. In this case we are directing it to the file ‘silverlightapp.xml’. If this was to contain the XAML of our earlier example in simple text form, and both these files were uploaded to a directory on your Web server, then opening the HTML page would result in our ‘Hello World!’ application appearing to the top-left of your browser.

The XAML that defines the Silverlight application need not reside in a separate file. It can instead be defined within the page that instantiates the plug-in using a special script block. For example, we could insert the following immediately before the ‘pluginHost’ div block in our HTML page above, which also shows off some of the special effects supported by Silverlight:

Code example. Click link below to donwload actual text.

Download complete code example

We reference this XAML block by changing the ‘source’ parameter for the Silverlight1 object as follows:

Code example. Click link below to donwload actual text.

Download complete code example

The hash character indicates that what follows references a script block on the current page. The other principle difference between this and our earlier XAML example is that we have placed a Rectangle object on the Canvas. This is a Shape element, as is the Line, Ellipse, Polygon and Polyline, and as such supports a wider range of display options. The RadiusX and RadiusY attributes round the corners of the Rectangle, while the Fill property allows us to specify a Brush object. In this case we have used the LinearGradientBrush to shade the Rectangle in a graduated blend of yellow and light blue.

Most of the other parameters supported by the Silverlight plug-in can be ignored at this stage. However ‘minRuntimeVersion’ can be useful if you want to ensure, for example, that version 2.0 is installed rather than version 1.0. This can be accompanied by ‘autoUpgrade’ which means that an attempt should be made to upgrade automatically in the event of too early a version being found. There is also the ‘OnLoad’ parameter which can specify a JavaScript function that should be run once the plug-in is loaded (more on that later).

If you want to know more about the options available when instantiating Silverlight, then the article ‘Instantiating a Silverlight Plug-in’ from Microsoft’s MSDN Library is a good place to start.

Using PHP with Silverlight
For the PHP developer, the important point is that the source for the Silverlight object can be anything that returns XAML, and that includes a PHP script. This opens up many possibilities. For example, the following PHP page uses Silverlight to display data extracted from a MySQL database:

Code example. Click link below to donwload actual text.

Download complete code example

Assuming this is part of the page ‘customers.php’ on our PHP server, then calling it with the following URL would cause Silverlight to display the name, city and postcode of the 134th customer in the database:

http://myserver.com/customers.php?ID=134

Having extracted the ID value from the query string, the code opens a connection to the database and then runs a query which gets the data for the customer specified and places it in the object $result. The function mysqli_fetch_array() extracts the data from $result into the array $row, from where it can be read and inserted into the XAML using the echo command.
This is far from production code, with little in the way of error checking, but it does serve to demonstrate how PHP can be used to generate a Silverlight application. For the sake of simplicity our example embeds the XAML within the page that instantiates the Silverlight control, but you could equally specify a PHP page as the source for the Silverlight control itself, as in the following snippet:

Code example. Click link below to donwload actual text.

Download complete code example

All that is required here is that the page clients.php return valid XAML code that can be rendered by Silverlight.

Adding user interaction with JavaScript
The Silverlight plug-in exposes a JavaScript API that allows any XAML element can be manipulated by JavaScript, in much the same way that you would program against the HTML Document Object Model (DOM) exposed by the page. Furthermore, Silverlight boasts a wide range of programmable events which opens up many possibilities for user interaction.

For example, in the following we have added an ‘x:Name’ attribute to the TextBlock element. This allows JavaScript to access and manipulate the element using the findName function. We have also attached an event handler stating that the JavaScript function changeText should be executed if the user depresses the left mouse button while the pointer is over the Canvas element:

Code example. Click link below to donwload actual text.

Download complete code example

We can now define the changeText function by adding the following to the page that instantiates the Silverlight object:

Code example. Click link below to donwload actual text.

Download complete code example

This script locates the element we want to manipulate using the findName function, and then sets its Text attribute to change from ‘Hello World!’ to ‘Goodbye!’ when the Canvas is clicked. One important point to note here is that the JavaScript is interpreted by the browser and not by the Silverlight plug-in. The x:Name attribute provides a handle that allows the findName function to reach into Silverlight for objects declared within the XAML code.

You can use these techniques to respond to a wide range of events. The API allows you to respond to simple movements of the mouse, or when the mouse pointer enters or leaves an object. You can respond to the depression of the left mouse button, and when it is released. Most objects respond to key up and key down events as well, and there are facilities for determining the key combination. The TextBox control supports a TextChanged event, while the PasswordBox control supports a PasswordChanged event and the Button control supports a Click event

One of Silverlight’s great strengths is this ability to manipulate anything you declare in your XAML code through a coherent object model. Check out the Silverlight Developer Center in the MSDN Library for a comprehensive reference to the whole API.

Interacting with a PHP Web Service
Most of the techniques discussed so far work with both versions of Silverlight. However Silverlight 2.0 opens up new possibilities for client-side processing as it includes a version of the .NET Framework and the Common Language Runtime (CLR) which allows it to run client-side code written in C#, Visual Basic and many other languages. The code for such programs is compressed into a single ZIP file together with the XAML definition and a manifest (also written in XML). The result is given the file extension XAP and referenced through the plug-in’s source parameter in the same way as we referenced our XAML file in the example above. When the page containing the plug-in is opened by the client, the XAP file is downloaded and unpacked, and then the code is compiled and executed.

This opens up further opportunities for the PHP programmer as such applications can make calls to Web services, and those Web services can be defined in PHP. For such an application to work the service has to be SOAP 1.1 compliant, and you will need to define a clientaccesspolicy.xml file if the service comes from a different domain to the application. This is to prevent cross-site forgery (see the article Making a Service Available Across Domain Boundaries for more on this).

It is also worth noting that Silverlight 2.0 also includes the Dynamic Language Runtime (DLR) which supports IronPython, IronRuby and Managed JScript. These languages are being developed at Microsoft’s open source project hosting site Codeplex. For further details see Silverlight Dynamic Languages SDK.

Choosing the Right Tools
While not a requirement, Microsoft has released a number of tools that would be useful to the PHP developer looking to work with Silverlight. Microsoft Visual Web Developer 2008 Express Edition is a useful Web page designer with full support for CSS, JavaScript and AJAX. It can also be used with Silverlight Tools for Visual Studio 2008 to automate production of much of the infrastructure behind a Silverlight application. Both can be downloaded from the Microsoft Web site free of charge.

Microsoft Expression Blend 2 is a professional graphic design tool that outputs XAML, allowing designers to create attractive user interfaces and to automatically generate the code required by Silverlight for its display. Alternatively increased support from the community means there are a growing number of third party XAML editors out there as well.

Sitting alongside Blend 2 is Microsoft Expression Web 2. Aimed at the professional Web designer, this latest release introducing many features that have been designed specifically for the PHP developer. There are menu options for inserting common PHP snippets, including pre-defined form, URL and session variables, server side includes and other structures. Furthermore, Expression Web 2 will render the page in Design View as though all the code, including server side includes, were in a single file, allowing you to see your code in action without leaving the editor.

Expression Web 2 understands PHP which means it will colour code language constructs intelligently, and there is full support for auto-completion so that you can see what functions and parameters are available to you as you write the code. Expression Web 2 also includes the PHP 5.2.5 runtime which you can use locally as a development server.

So Silverlight has a great deal to offer the PHP developer – something that Microsoft is clearly recognising with its support for PHP in Expression Web 2. Trial versions of Microsoft’s Expression range are available for download.

[Main image by Pathfinder Linden]

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from either HTML, CSS or Wordpress.

Start learning

Treehouse

Our mission is to bring affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world.

Comments

76 comments on “Silverlight for PHP Developers

  1. In the very first code example in this post, you have type=”application/x-shockwave-flash” — that should be type=”application/x-silverlight-2″, no?

  2. As I was reading through the article, this line caught my attention: $query=”SELECT * FROM customers WHERE ID=$ID”;You should never write queries like this, and although you might be familiar with SQL injections (?), I don't think posting stuff like this in a popular blog is a good thing. Even for an example! You should at least add mysql_real_escape_string($ID) to your query.PHP is very easy to use — and abuse, and inexperienced programmers that read your blog post may not understand the security implications of what they do (unfortunately, this is common). Also see http://phpsec.org/projects/guide/3.html#3.2Apart from that, nice introduction to Silverlight…

  3. As I was reading through the article, this line caught my attention:

    $query=”SELECT * FROM customers WHERE ID=$ID”;

    You should never write queries like this, and although you might be familiar with SQL injections (?), I don't think posting stuff like this in a popular blog is a good thing. Even for an example! You should at least add mysql_real_escape_string($ID) to your query.

    PHP is very easy to use — and abuse, and inexperienced programmers that read your blog post may not understand the security implications of what they do (unfortunately, this is common).

    Also see http://phpsec.org/projects/guide/3.html#3.2

    Apart from that, nice introduction to Silverlight…

  4. Good point. I'd also recommend to 'tear out' variables, e.g.:$query=”SELECT * FROM customers WHERE id=”.mysql_real_escape_string($id);$query=”SELECT * FROM customers WHERE username LIKE '%”.mysql_real_escape_string($username).”%'”;

  5. Good point. I'd also recommend to 'tear out' variables, e.g.:
    $query=”SELECT * FROM customers WHERE id=”.mysql_real_escape_string($id);

    $query=”SELECT * FROM customers WHERE username LIKE '%”.mysql_real_escape_string($username).”%'”;

  6. A few points:- The “object” examples seems to be completely wrong, such as the mime type (application/x-shockwave-flash), there being a comma in the missing data attribute, and there is mention of a “Get Silverlight” image for those without the plug-in (which I should point out, most people will see, and then leave the site).- This is the first time I've seen the source code for a Silverlight object, but how is this any different to SVG (W3C) or the canvas element (started by Safari, and to be included in HTML5).- The MySQL example has an SQL injection venerability… look at mysqli_real_escape_string() or prepared statements.- The example “customers.php” does not show any example output… and I would suggest that if you only need those three values (name, city and postcode), they should be specified in the SQL, rather than using “*” to get all values.- The section around “Adding user interaction with JavaScript” (a heading?) seems to be missing an example of some XAML.- Am I the only one who doesn't like the idea of C#/VB code being downloaded and being run on my computer, in an environment created by Microsoft? not to mention that this “Silverlight Standard” is being created by a single (closed) company, and appears to be trying to mimic the work already done by SVG?Sorry to be so negative, but could you at least proof read this first (in he same way that the “Open XML” specification should have been checked before publication).

  7. A few points:

    - The “object” examples seems to be completely wrong, such as the mime type (application/x-shockwave-flash), there being a comma in the missing data attribute, and there is mention of a “Get Silverlight” image for those without the plug-in (which I should point out, most people will see, and then leave the site).

    - This is the first time I've seen the source code for a Silverlight object, but how is this any different to SVG (W3C) or the canvas element (started by Safari, and to be included in HTML5).

    - The MySQL example has an SQL injection venerability… look at mysqli_real_escape_string() or prepared statements.

    - The example “customers.php” does not show any example output… and I would suggest that if you only need those three values (name, city and postcode), they should be specified in the SQL, rather than using “*” to get all values.

    - The section around “Adding user interaction with JavaScript” (a heading?) seems to be missing an example of some XAML.

    - Am I the only one who doesn't like the idea of C#/VB code being downloaded and being run on my computer, in an environment created by Microsoft? not to mention that this “Silverlight Standard” is being created by a single (closed) company, and appears to be trying to mimic the work already done by SVG?

    Sorry to be so negative, but could you at least proof read this first (in he same way that the “Open XML” specification should have been checked before publication).

  8. Hi Craig,Thanks for pointing that out. This was our fault, not Marks. For some reason, WordPress butchered the code when we published it.It's been amended now.Thanks again,Ryan

  9. Hi Craig,

    Thanks for pointing that out. This was our fault, not Marks. For some reason, WordPress butchered the code when we published it.

    It's been amended now.

    Thanks again,
    Ryan

  10. I don't know…..Early on, Microsoft technologies seem to have some bugs on Microsoft platforms such as ASP>NET, SQL Server, etc. In my experience hosting, Microsoft OS and PHP don't always place nice. Now you're adding another layer on top of that? I'll have to take a wait and see approach on this one. Not ruling it out, just needs some more time to see how it performs.

  11. I don't know…..Early on, Microsoft technologies seem to have some bugs on Microsoft platforms such as ASP>NET, SQL Server, etc. In my experience hosting, Microsoft OS and PHP don't always place nice.

    Now you're adding another layer on top of that? I'll have to take a wait and see approach on this one. Not ruling it out, just needs some more time to see how it performs.

  12. Cool. I suggest the Zend_AMF library for anyone who wants to use PHP to interact with Flash/Flex. I'm pretty sure it was developed by the AMF and Zend guys in tandem.

  13. Cool. I suggest the Zend_AMF library for anyone who wants to use PHP to interact with Flash/Flex. I'm pretty sure it was developed by the AMF and Zend guys in tandem.

  14. I hve just started learning PHP, it is good to know about silverlight for PHP developers, Very informative and easy understanding post, thxs for this :)

  15. Silverlight is a super tool. I would have argue that Expression Web supports PHP. A fistful of stubs (small fist at that). For the asp.net developer it's a great combo though.

  16. Silverlight is a super tool. I would have argue that Expression Web supports PHP. A fistful of stubs (small fist at that). For the asp.net developer it's a great combo though.

  17. So I can output stuff without generating any binaries, very cool. But can I _program_ it without compilation, or is it limited to XAML stuff (i.e. static only)?

  18. Sitting alongside Blend 2 is Microsoft Expression Web 2. Aimed at the professional Web designer, this latest release introducing many features that have been designed specifically for the PHP developer. There are menu options for inserting common PHP snippets, including pre-defined form, URL and session variables, server side includes and other structures. Furthermore, Expression Web 2 will render the page in Design View as though all the code, including server side includes, were in a single file, allowing you to see your code in action without leaving the editor.New York Psychic

  19. Sitting alongside Blend 2 is Microsoft Expression Web 2. Aimed at the professional Web designer, this latest release introducing many features that have been designed specifically for the PHP developer. There are menu options for inserting common PHP snippets, including pre-defined form, URL and session variables, server side includes and other structures. Furthermore, Expression Web 2 will render the page in Design View as though all the code, including server side includes, were in a single file, allowing you to see your code in action without leaving the editor.

    New York Psychic

  20. You can indeed program the Silverlight without compilation – using either JavaScript in the HTML page calling into the XAML DOM or using the Dynamic Language Runtime (DLR) – so using IronRuby, IronPython, or again JavaScript (using managed JScript).http://silverlight.net/learn/dynamiclanguages.aspx might be a useful reference. Incidentally, the DLR, IronRuby & IronPython are all open source.

  21. You can indeed program the Silverlight without compilation – using either JavaScript in the HTML page calling into the XAML DOM or using the Dynamic Language Runtime (DLR) – so using IronRuby, IronPython, or again JavaScript (using managed JScript).

    http://silverlight.net/learn/dynamiclanguages.aspx might be a useful reference. Incidentally, the DLR, IronRuby & IronPython are all open source.

  22. Hi Pies,Yes you can program it without compilation using either JavaScript in the html pages talking to the XAML DOM or using a language like Managed JScript (JavaScript), IronRuby or IronPython in the Dynamic Language Runtime (DLR).A good intial reference for this is http://silverlight.net/learn/dynamiclanguages.aspx. Incidentally, the DLR, IronRuby & IronPython are all open source.-Mark

  23. Hi Pies,

    Yes you can program it without compilation using either JavaScript in the html pages talking to the XAML DOM or using a language like Managed JScript (JavaScript), IronRuby or IronPython in the Dynamic Language Runtime (DLR).

    A good intial reference for this is http://silverlight.net/learn/dynamiclanguages.aspx. Incidentally, the DLR, IronRuby & IronPython are all open source.

    -Mark

  24. Hi MarkThis is a great but but it doesn't work that well with silverlight20 or higher.Can u please show how to do that in higher versions of silverlight.

  25. Hi Mark
    This is a great but but it doesn't work that well with silverlight20 or higher.
    Can u please show how to do that in higher versions of silverlight.

  26. Wow..This article is a detailed one.. I find it amazing that Microsoft can come with these kinds of programs.. No wonder its one of the leading companies all over the world.. I may not be an expert in programming but I think I understood the concept of silverlight.. Thanks thinkvitamin and thanks microsoft.. HGV Training

  27. Wow..This article is a detailed one.. I find it amazing that Microsoft can come with these kinds of programs.. No wonder its one of the leading companies all over the world.. I may not be an expert in programming but I think I understood the concept of silverlight.. Thanks thinkvitamin and thanks microsoft..

    HGV Training

  28. Excellent! Thanks for doing this…it's really nice to know that I'm not alone on a lot of these things.

  29. Excellent! Thanks for doing this…it's really nice to know that I'm not alone on a lot of these things.

  30. I think Microsoft browser plug-in might seem an odd target for the PHP developer, more used to working with open source platforms such as Linux, Apache and the MySQL database server. However there is much about Microsoft Silverlight that makes it a good match to such technologies. This sounds good for php developers.

  31. Nice article on Silverlight for PHP Developers. I notice that a few copy typing errors have been introduced in the publication process affecting some of the code samples. I’ll try and get them sorted out.

  32. PHP is very easy to use — and abuse, and inexperienced programmers that read your blog post may not understand the security implications of what they do (unfortunately, this is common). Its benefit is it has much options and i would like to say that it is the best.
    .

  33. Pingback: Carsonified » Silverlight for PHP Developers | Webmaster Tools

  34. Hi all,
    This is wonderful tutorial about how to Connecting Silverlight To Our PHP Web Service.
    our important goal is to support the Silverlight (2.0) platform. Shortly Silverlight is a cross-browser platform that can be used for developing client-side components that run in the web browser and contain rich media, graphics and can interactively communicate with the user. The language that can be used for writing Silverlight code can be in general any .NET language, so our goal is to allow using PHP by making Phalanger compatible with Silverlight.
    thanks guys keep it up…

  35. Hey Mark Quirk,

    Its so easy like we use php code for flash file(.swf). As I seen silver light is also start booming in multimedia market sample codes you provide here will really useful for php developers. Thanks for sample codes.

    • Do you like to work on ctontract basis ? As php developer if Yeah then let me know i have big project on php…we should hire you and take our work.