Table of Contents
Title Page
Copyright Page
Epigraph
About the Authors
About the Translator
Foreword
Preface
Acknowledgments
Target Audience
Book Structure
Versions, Cutting Edge, and Bleeding Edge
Coding Conventions
Chapter 1 - Introduction
1.1 Why SilverStripe?
1.2 History
1.3 Future
1.4 Conclusion
Chapter 2 - Installation
2.1 System Requirements
2.2 Preparation
2.3 Installation
2.4 Useful Software
2.5 Database Management
2.6 Support
2.7 Conclusion
Chapter 3 - Architecture
3.1 Introduction
3.2 MVC- Model View Controller
3.3 ORM - Object Relational Mapping
3.4 Directory Structure
3.5 Modules and Widgets
3.6 Themes
3.7 Configuration
3.8 Conclusion
Chapter 4 - First Steps
4.1 Our Project: Job Portal and User Group
4.2 Creating the Page Structure
4.3 Inserting Page Content
4.4 Managing Files and Images
4.5 Versioning
4.6 Comments
4.7 Simple Contact Form
4.8 Creating New Users
4.9 Themes
4.10 Conclusion
Chapter 5 - Development: Job Postings
5.1 Job Categories as a Page Type
5.2 Job as a DataObject
5.3 Relations Between DataObjects
5.4 Creating the Interface
5.5 Creating Templates
5.6 Custom Forms
5.7 Email Notification
5.8 Integrating the Blog Module
5.9 Search Engine Optimization
5.10 Conclusion
Chapter 6 - CRM
6.1 Where are we Headed?
6.2 Datamodel
6.3 Using ModelAdmin for Data Management
6.4 Multi-page Registration Form
6.5 Skills as Tags
6.6 File Uploads for References
6.7 Searching DataObjects
6.8 Generic Views Using CollectionController
6.9 Defining Access Permissions
6.10 Web Services Using RESTfulServer
6.11 RSS Feeds for Jobs
6.12 Conclusion
Chapter 7 - Security
7.1 Cross-site Scripting (XSS)
7.2 Cross-site Request Forgery (CSRF)
7.3 SQL Injection
7.4 Directory Traversal
7.5 Sessions
7.6 Conclusion
Chapter 8 - Maintenance
8.1 Environment Types
8.2 Configuration of Multiple Environments
8.3 Version Control using Subversion
8.4 Backup
8.5 Upgrade
8.6 Error Handling
8.7 Performance
8.8 Conclusion
Chapter 9 - Testing
9.1 Test-driven Development
9.2 Installing PHPUnit
9.3 Running Tests
9.4 Unit Tests for the Model
9.5 Functional Tests for the Controllers
9.6 Conclusion
Chapter 10 - Localization
10.1 Character Sets and Unicode
10.2 Translating Templates and Code
10.3 Translatable: Translating Database Content
10.4 Conclusion
Chapter 11 - Recipes
11.1 Prerequisites
11.2 Customizable Page Banner
11.3 Branding the CMS Interfaces
11.4 Full-text Search for Websites
11.5 Redirecting from Legacy URLs
11.6 Simple Statistics using TableListField
11.7 Showing Related Pages
11.8 CSV Import using CSVBulkLoader
11.9 A Fully Flash-based Website Driven by SilverStripe
11.10 Conclusion
Chapter 12 - Extending
12.1 Different Ways to Extend SilverStripe
12.2 Extending Core Functions
12.3 Creating Custom Modules
12.4 Creating Custom Widgets
12.5 Conclusion
Chapter 13 - Useful Modules
13.1 E-commerce
13.2 Forum
13.3 Gallery
13.4 Flickr Service
13.5 Youtube Gallery
13.6 Spam Protection: Mollom and Recaptcha
13.7 Auth_External
13.8 Auth_OpenID
13.9 Subsites
13.10 CMS Workflow
13.11 Site-tree Importer
13.12 Geospatial Modules
13.13 Conclusion
Index
© 2009 by Galileo Press
Galileo Computing is an imprint of Galileo Press, Bonn (Germany), Boston (USA). German Edition first published 2008 by Galileo Press.
All rights reserved. Neither this publication nor any part of it may be copied or reproduced in any form or by any means or translated into another language without the prior consent of Galileo Press, Rheinwerkallee 4. 53227 Bonn, Germany.
Galileo Press makes no warranties or representations with respect to the content hereof and specifically disclaims any implied warranties of merchantability or fitness for any particular purpose. Galileo Press assumes no responsibility for any errors that may appear in this publication.
This edition first published 2009 © 2009 John Wiley and Sons, Ltd
Registered office
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.
The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.
ISBN 978-0-470-68183-1
A catalogue record for this book is available from the British Library.
Typeset in 10/12 Optima by Laserwords Private Limited, Chennai, India
“I feel SilverStripe is a great example of a well-constructed open source project.”
Chris DiBona, Open Source Programs Manager, Google Inc.
Publisher’s Acknowledgements
Some of the people who helped bring this book to market include the following:
Editorial and Production
VP Consumer and Technology Publishing Director: Michelle Leete
Associate Director - Book Content Management: Martin Tribe
Associate Publisher: Chris Webb
Executive Commissioning Editor: Birgit Gruber
Assistant Editor: Colleen Goldring
Content Editor: Claire Spinks
Publishing Assistant: Ellie Scott
Copy Editor: Andrew Finch
Composition: Laserwords Private Ltd
Marketing
Senior Marketing Manager: Louise Breinholt
Marketing Executive: Kate Batchelor
About the Authors
Steven Broschart has been active for 6 years as an advisor and developer at one of Germany’s leading online marketing agencies, cyberpromote GmbH. Aside from developing PHP and Ruby on Rails business applications and coordinating key accounts for SEO, he advises his clients on selecting appropriate open source software. Steven is a regular author in relevant industry publications.
Ingo Schommer freelanced as a PHP and Flash developer for several years prior to joining SilverStripe in 2006 as a senior developer. At SilverStripe, Ingo analyses and builds modern web applications, making sure that they work well in a browser and not just on paper. He has a key role architecting and implementing core functionality in the SilverStripe platform, and facilitates involvement of the open-source community.
About the Translator
Julian Seidenberg has a background in developing web applications using PHP and Java and has worked in a variety of software engineering roles. He is also a developer at SilverStripe and holds a PhD in Semantic Web technology from the University of Manchester.
Foreword
Sigurd Magnusson
Co-founder and Chief Marketing Officer, SilverStripe Ltd
Thanks for buying the book! After countless long days and nights, it’s a real joy to see it come to fruition.
In 2000, the dream of the SilverStripe project began: to make a fantastic software platform to build and manage websites. Our company SilverStripe Ltd, which had its fair share of geeks, was in the business of building websites for customers. We found the tools out there didn’t suit us, and certainly didn’t suit our customers. Tools were either too technical, which suited us fine but confused our clients, or were simple enough for our non-technical customers, but insulted us with poorly constructed HTML and limited us from building sophisticated website features. So, we committed to make a system that let professional, experienced web developers build innovative websites which can then be passed, in confidence, to non-technical people to manage.
Several years passed, and by 2006 we had a few hundred customers. We had always sought to make the product global, but because we were the only one developing SilverStripe, adoption was limited to our home country, New Zealand. We were working hard on an entirely rewritten version of SilverStripe, v2.0, and agreed that if we were to make it successful, it had to be released as free software, with a loyal community of developers around it.
In late 2008, we celebrated two years of being open source. It was inspiring to see how quickly we’d moved forward. We had surpassed 100,000 downloads, been invited into the Google Summer of Code, had a growing community with external contributors, and our software was powering some impressive websites. For example, a SilverStripe-powered website, http://demconvention.com/, served millions of visitors in a 100 hour span as Barack Obama accepted his nomination as the presidential candidate for the United States Democratic Party.
However, writing the software is only half the battle: you also need documentation that teaches the world on how to take advantage of it. If there was one thing I wanted to improve, it was our documentation. So I’m very humbled by the months of work that Ingo and Steven have put into writing a book while holding down their 9 to 5 jobs. Their effort provided the German text that has now been translated into the English edition you’re holding. It was very rewarding to see the book come out initially in Germany, because it showed just how international SilverStripe had become, and that a country renown for high quality engineering had given the thumbs up to SilverStripe! With this book now in English, we shift SilverStripe into a new gear, which is very exciting.
The concept of SilverStripe relies on us building up a community of developers, and so we hope that over time you will join us by emailing feedback, submitting code, and fixing bugs. We also hope to see your websites uploaded to the community showcase at http://silverstripe.org/showcase/!
In the years since we started SilverStripe, the concept of elegant, web-standard HTML and CSS has shifted from obscurity to being the norm. The idea of writing PHP in an elegant maintainable fashion, complete with object-oriented code, unit tests, and following the MVC pattern is still new to lots of people, but growing in popularity. However, having read the book, we hope that you can appreciate the other evolution of the web we’ve been anticipating for years: that the combination of a framework, a CMS product, and extension modules can together save developers a huge amount of development time by offering what they need out-of-the-box, while offering a huge potential for extension and innovation.
Welcome to the SilverStripe community!
Preface
Steven Broschart
Co-author of this book, and early member of the SilverStripe open source community.
It wasn’t too long ago when a fellow developer at work asked me to look at his screen. He had stumbled across some new technology, and asked: ‘Hey, have you heard about this?’ All too often such questions are answered with a ‘Yeah. Completely useless!’, but sometimes the answer is ‘No’. It’s in those times that a feeling of anxiety creeps in - did I miss a potentially groundbreaking development on the Internet? In this case I decided to defer my answer, and stopped what I was doing to investigate further.
It’s a good thing to keep in mind that in our current working environment every person is basically a human content-filter who must grapple with the daily excess of digital information. New products and ideas confront us so often, they don’t get the attention they deserve. Hence, a presentation of a ‘cool new thing’ has only a few seconds of your attention in which to grab your interest, as every marketing guy will tell you.
As you might have guessed, my colleague was showing me SilverStripe for the first time, and he succeeded in quickly gathering my interest. The fact that you’re reading this book probably means that you’re starting with a certain eagerness towards this ‘new thing’, too.
For several years now, I’ve been a consultant and developer in an online marketing agency that specializes in search engine optimization and usability. This means that I’ve developed a number of internal systems and a fair share of websites. A major internal focus was ensuring a quick and flexible development process. In this context we trialled a bunch of content management systems - scoring them against our set of requirements. Having reviewed several systems so far, I couldn’t wait to see what SilverStripe had in store. It seemed to be sufficiently different from the ‘big players’ to capture our interest. The ease with which usually complex tasks were solved in SilverStripe was promising and exciting. We liked what we saw and our agency began adopting SilverStripe in a big way. Since then, our experience has supported our positive first impression.
During the last couple of years, certain programming concepts have become very popular in the website and web-application development space. In particular, people have become far more interested in rapid development, technical elegance, robustness, and building increasingly interactive websites. Although these concepts aren’t necessarily new, most web developers have a fairly informal development methodology - especially those writing in PHP. Writing code in a well-structured way was not common place. One event that influenced this trend was a framework called Ruby on Rails (http://www.rubyonrails.com/), which was increasing in popularity. This raised the game for everyone: The carefully structured architecture, methodology, and principles of that framework rubbed off and became best practices, which the whole web industry began to discuss, embrace, and challenge.
SilverStripe is written in PHP and has an architecture very much modeled on these contemporary best practices. SilverStripe combines the advantages of a CMS application with a powerful framework ‘under the hood’. Time-intensive programming sessions for conceptually simple features should be a thing of the past, which shouldn’t only delight the programmer, but also the manager who has to justify budgets and timeframes. After all, time and money are some of the primary factors determining the success of a project. After reading through the first tutorials it became clear to me that in this case these weren’t just empty marketing phrases. Because care was put into its architecture, this product was able to give me a glance at advanced functionality without knowing its inner workings. Its shallow learning curve dwarfed many other competitors in the same space.
Anyway, back to the story. Apart from playing around with new shiny web toys, I’m a freelance author in Germany on subjects from search engine optimization to usability to web technologies. Driven by my first SilverStripe experiences, in 2008 I published an article on SilverStripe in a popular German industry magazine called PHP Magazin (see announcement at http://silverstripe.com/silverstripe-main-feature-of-german-php-magazin/).
While writing this article, I made contact with the company behind the software to check a few facts - the aptly named web development shop SilverStripe Ltd, based in Wellington, New Zealand. In particular I reached out to Ingo Schommer, a senior developer at the company. Ingo is a fellow German, who became attracted to SilverStripe after battling other open source CMS products - software too often plagued by complex configuration and the feeling of spending more time disabling features than actually implementing stuff. Emigrating from Germany to New Zealand in order to change this situation might seem like a desperate measure, but it worked out well.
The magazine article was so well received that it supported the idea of writing the book you’re now reading. There was no print material to show interested developers a straightforward learning path to implement their own solutions in SilverStripe. The magazine article demonstrated demand, and so I asked Ingo to be a co-author, and sought a German publisher, Galileo Computing. Both promptly agreed to produce the book.
Writing the German book took several months of intense collaboration across continents (from Wellington to Munich and back), by which time the CMS had become increasing popular in the German market - which geographically couldn’t be much further from New Zealand! The German book was released in early 2009, and sold sufficiently quickly that it had to be restocked on Amazon.de days after the book launched.
Of course, there’s a larger audience of English readers for a SilverStripe book, and plans by SilverStripe Ltd to have an English book predated me even learning about their software. Translating the German book provided a sensible way to finally achieve this goal, and what you’re reading now is the work of several SilverStripe Ltd staff members adapting the work into English.
Now please follow us on a quick tour through SilverStripe, and we’ll show you what’s behind the buzz. We hope that you have as much fun reading this book as we had writing it. All right, that was quite a stereotypical way to finish the preface of a technical book, but anyway: Enjoy!
So, to answer my colleague: Thanks for your discovery, Robert. No, didn’t know this system!
Acknowledgments
Although the names of the authors are prominently placed on the cover of a book, the reality is that such an exhaustive guide couldn’t happen without further support. Special thanks go towards our original publisher in Germany, Galileo Computing, especially to our editor Stephan Mattescheck who supported us throughout what happened to be the first book publication for the two of us. And consequently, a big thank you to Wiley Publishing for picking up this work and agreeing to make it available to a much larger English-speaking community, particularly to Martin Tribe and Colleen Goldring, our editors at Wiley, for their patience and giving us a chance to polish content rather than translate word-for-word. ‘Dankeschön’ to Sigurd Magnusson, who helped us navigate the unfamiliar waters of book publications and spent long nights reviewing content - the book got a lot more ‘digestible’ with your input! Thanks to Andy Finch for copy-editing our ‘Germenglish’, and to Sibylle Schwarz for keeping us focused. We’d like to thank SilverStripe Ltd, who ‘lent’ us considerable resources for the translation effort. Massive thanks to Julian Seidenberg for unexpectedly spending his first weeks as a developer with SilverStripe Ltd. translating the book rather than writing code. Kudos to our ‘beta’-readers Andy Adiwidjaja, Claudia Liersch, Joon Choi, Tobias Hoderlein, Sam Minnée; without your comments and ideas the book would’ve been only half as good. And ‘last but not least’ thanks go to our families and friends, who lost us to text processing and late night Skype meetings for several months - you’re the best!
Target Audience
This book mainly targets PHP developers who’re looking for new solutions to quickly build websites, big and small. Because SilverStripe uses some techniques and paradigms that aren’t necessarily widespread knowledge to PHP developers, we make some suggestions here for recommended further reading.
If you’re not a developer but are evaluating SilverStripe as a platform, you should still find many parts of this book useful. The book doesn’t delve deep into code until Chapter 5, ‘Development’, and even then, there are plenty of explanations, screenshots, and summaries that will give less technical people meaningful insight into SilverStripe.
Of course we also address the actual users of the system, the content authors who manage websites with this tool. If this is you, Chapter 4, ‘First Steps’, is the one to focus on, because this is where we provide a summary of the CMS content editing interface.
For the more technical chapters of the book, we assume that you have some experience with PHP and that you’re comfortable with object-oriented programming. Perhaps you’re already familiar with Java, in which case you should feel right at home with the object-oriented capabilities of PHP. If you feel a bit lost with terms such as objects, classes, interfaces, or inheritance, we’d like to recommend a book covering these basics: PHP 5 For Dummies by Janet Valade (published by Wiley; ISBN: 978-0-7645-4166-7). The official PHP website at http://php.net/can of course also be used as a primer.
SilverStripe is based on PHP version 5, released in 2004. Because it uses the full capabilities of this version, much of its architecture is impossible to achieve in the outdated PHP4. We’ll describe some of these capabilities as we go along, but developers who are used to PHP4 might need to brush up their knowledge about the object-oriented coding to take advantage of this book.
Because this book is aimed at developers, we also assume a basic familiarity with standard web technologies such as HTML, JavaScript, and CSS. We don’t ask you to write anything advanced with them in this book - although once you’ve finished the book, having strong skills in those languages will enable you to make great SilverStripe websites!
Book Structure
This book begins with a mostly non-technical review that describes the underlying principles, technologies, and architecture, as well as the installation of SilverStripe. After everything is set up both conceptually and on your own webserver environment, we dive into code with an example website and application. Building this example project will span multiple chapters and provide a coherent learning path. The later chapters become more independent of this example and can be worked through in isolation if you wish - they relate to topics such as internationalization, security, and performance. The book ends with a set of code recipes that demonstrate useful techniques, and a summary of the most useful extension modules.
Book website: Updates and source code
We’ve tried our best to provide a perfect book without any mistakes. If that’s not the case every now and then, you can find errata and corrections as well as up-to-date information on a website dedicated to the book: www.wiley.com/go/silverstripe.
The website is also where you can download the source code mentioned throughout the book.
Terminology: CMS, frontend and backend
• Content Management System (CMS): Although we sometimes refer to the entire software as ‘the CMS’, in the book this term normally refers to the graphical user interface that the software provides to manage your website content.
• Backend: The generic name for an authenticated interface, with the CMS being one prime example.
• Frontend: The public-facing website.
Versions, Cutting Edge, and Bleeding Edge
What might sound like the title of a horror film on first reading is actually a way to describe the status of a technology project. If you hear the term Cutting Edge in relation to new features in software, you’re dealing with fairly new developments, which most likely aren’t yet contained in a stable release. Bleeding Edge is even further ahead of this, meaning that features and implementations are subject to change, and probably need some further testing - you can metaphorically cut yourself if you’re not careful.
We raise this topic because toward the end of the book, you come into contact with some of the fresher and younger features of SilverStripe. Due to the software’s modular architecture, it’s easy to update individual components later as such features mature.
In our code examples we’re referring to SilverStripe 2.3.3, which was released mid-2009. If you’re using a newer version to follow our examples, please make sure to read the update notes at http://doc.silverstripe.com/doku.php?id=upgrading. If you need more details, please have a look at the changelog at http://open.silverstripe.com/wiki/ChangeLog/.
Coding Conventions
Code shown is this book is typically standard PHP, which follows the official SilverStripe coding conventions that you can read online at http://doc.silverstripe.com/doku.php?id=coding-conventions. It should therefore need no further explanation. Something we do want to point out is how we treat updating files you’ve already worked on - we generally show the new code without repeating the whole listing. The existing (but not shown) code is noted by an inline comment. Leave your current code as is, and write around it:
// ... PHP/JavaScript Omission /* ... */ CSS Omission <!-- ... --> SilverStripe Template Omission
But enough introduction, let’s get on with the tour!
1
Introduction
At it’s heart, the role of a content management system (CMS) is to make it easier to publish content to websites and intranets. It may be used to allow the owner of a one-person company to update his or her website without needing a website developer or learning HTML skills. Or, in a multinational company, it might allow a skilled web team across various cities to manage a complex assortment of updates to products, services, promotions, and news in multiple languages. Either way, it automates various tasks, and makes building a website more efficient and reliable.
Countless products are available based on such a promise, however, all of varying sophistication, histories, programming languages, and geographical dominance. The decision-makers and developers involved in selecting a CMS work in fast-paced environments and are creatures of habit: They have personal favorites to solve the challenges their job provides. Why go through the trouble of trying a new CMS?
1.1 Why SilverStripe?
One thing up front: SilverStripe is not the answer to all problems that you might face throughout the development of a website or web application. No software is ever a silver bullet for every situation. You must determine selection criteria based on your needs, skills, budgets, and timeframes, and select the most relevant tool based on those criteria. That said, SilverStripe is intended to be both used out-of-the-box and for major customization. This makes it particularly interesting when building websites - because everyone seems to relish having a unique set of needs in terms of design, information architecture, content, features, integration with other systems, business policies, and so on.
The following pages list some major benefits of SilverStripe, and describe how it stands out in a crowded CMS market. We acknowledge that the information here is concise, but this will help you refer back to an overview even when you’re familiar with SilverStripe. We try to keep things brief here; the rest of the book will substantiate the claims made, as you begin to build stuff using the software.
1.1.1 An Application and a Framework
SilverStripe is really two products in one: The SilverStripe CMS and the Sapphire Framework. There are plenty of CMS applications and quite a few programming frameworks in the marketplace; however, SilverStripe is very rare in that it tightly weaves the two concepts together.
You will need to read the whole book to understand entirely the value of this unity, but the value is much greater than the sum of its parts. In other words, the CMS has plenty of good things about it, as does Sapphire. However, with them joined so closely, their collective value is multiplied. The closeness of the two concepts is possible because Sapphire and the CMS were created in tandem, by the same people.
1.1.2 CMS for Content Authors and Framework for Developers
One fundamental reason for SilverStripe being divided into two sections is to honor the needs of two quite separate types of people who use the software. The CMS backend is designed to allow non-technical users to update web pages, images, links, moderate blog comments, and so on. This is the area where content authors do their content management, and anything technical is strictly kept out of sight for the sake of good usability.
The framework is used to build the underlying website, and isn’t for content authors. You ‘use’ the framework by actually writing HTML, CSS, JavaScript, and object-oriented PHP code. The framework enables beginning PHP programmers to achieve quite powerful things, by following recipes and tutorials as shown in this book and elsewhere. However, the framework is targeted at savvy PHP programmers. For them, Sapphire allows much more creative freedom in building complex websites quickly and robustly.
Many other CMS products don’t have such a separation. In other words, in many systems the CMS user interface is shared by content authors and developers, which typically makes the interface too complicated for it’s primary users: the content authors. In some systems, developers perform their work mainly through a graphical configuration interface, which is usually more limiting than raw programming. A graphical interface to accommodate sophisticated needs for developers would require a bewildering set of options, which would add complexity and bloat the software, when the idea in question is likely to be far more efficiently expressed as a few lines of code.
So, this separation in SilverStripe means that the CMS backend can be designed for non-technical users, and the framework can confidently concentrate on being suitable to technically-minded web developers (see Figure 1.1 for an overview of the SilverStripe system).
Figure 1.1 SilverStripe system overview.
1.1.3 Clear Separation of Concerns
As we begin to suggest above, a core principle in SilverStripe is the separation of concerns. In this introduction, we use that term loosely to mean organizing the software into all sorts of logical divisions. You will be familiar with how HTML and CSS separate the concerns of markup and presentation, and that JavaScript is used to allow for the concern of behavior and interaction on a web page. This structure provides many benefits such as enabling reuse: change a single style in a CSS file, and so long as you’ve stuck to best practices in your HTML, styles throughout the whole website will update, saving time and maintaining consistency.
SilverStripe follows this principle: Update an isolated area of the system that deals with a particular function, and it produces logical, robust, and application-wide changes. Without this architectural principle, changing a feature of your website means changing a few lines of code here, a few lines of code there, and finding that each step of the way upsets unrelated parts of your website. This domino effect suddenly turns a small change into a major coding and testing fiasco. SilverStripe’s architecture therefore helps to keep code changes proportionate to the effort needed to implement them. However, like the HTML, CSS, and JavaScript example, this reward is only given to those who carefully architect their SilverStripe application to its best practices.
Let’s highlight a few examples relating to this principle:
• Avoid repitition with the Sapphire framework.Sapphire supports the concept of writing the logic of your website once. For instance, if your website deals with selling T-shirts, you define that a T-shirt has an attribute ‘color’ in one place in your code. You don’t have to write redundant code elsewhere to explain that T-shirts have colors; the template, CMS, and even the database will automatically be updated based on your single declaration. This principle is commonly called Don’t repeat yourself (DRY ).
• No need to change database schema manually. This important point is hinted at above: SilverStripe will inspect your code for the tables and fields it needs, and update the schema accordingly. This makes keeping your database schema in sync with your PHP code a beautiful thing.
• Separates the PHP logic into the Model and the Controller. You’re probably familiar with separating PHP logic from HTML templates, but SilverStripe goes one step further. This is a very integral part of Sapphire, so let’s pause for a moment to investigate this in the following box.
Model View Controller as a central concept
The Model View Controller (MVC) concept is one of many design patterns that have been identified as good programming architecture. A design pattern is essentially a structured way to document the solution to a specific problem in computer science, a term made popular by the ‘Gang of Four’ in their book Design Patterns: Elements of Reusable Object-Oriented Software (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, published by Addison-Wesley). The three parts, Model, View, and Controller, describe the main roles of any application built with SilverStripe:
• The Model is responsible for maintaining the state in the application. It’s basically data: Some of it might be transient and only live within a web request, whereas other data might be permanently stored in a database. You can think of the Model as essentially the database schema you have for a website. We elaborate on this simplistic definition in later chapters.
• A View displays data that’s collected from the Model, usually through a template on a website or application frontend. One Model might have many Views: The list of forum users on your website might have a ‘public view’ and a ‘backend management interface view’. In both of these views, the used Model logic would be the same: The separation into different roles avoids code duplication and clarifies responsibilities.
• The Controller manages the layer in between the Model and View, and passes data between them. It’s the ‘glue’ of an application. It might take a new forum submission from a View, and tell the model to store it in the database. Although the actual input form is rendered in the View, the Controller is responsible for processing it. The Controller, for instance, would ensure that the submitter can post to this forum, and might send out emails to moderators or people subscribed to the forum. To clarify, the Model should not be responsible for such logic, and instead just store the data once the Controller has figured out what needs storing and how. Using the example here, separating the Model and Controller shows how you can have different form processing logic (multiple Controllers) making reuse of the Model.
All three roles work closely together. It’s just important to understand what goes where on a conceptual and practical level. If that sounds a bit too abstract for you at the moment, don’t despair. MVC is a central concept in SilverStripe, and we’ve dedicated an in-depth explanation to it in Chapter 3, Section 3.2, ‘MVC - Model View Controller’.
• Object Relational Mapper. The PHP code throughout SilverStripe is heavily object-oriented rather than procedural code, and this architecture extends to how you access the database. This maintains a unified approach to processing data both in and out of your database: you deal with objects rather than flipping constantly between arrays, methods, objects, SQL syntax, and so on. This lessens the lines of code used to create, remove, update, and delete data in your database, and improves readability. It also marries the database schema more closely to your PHP code, thereby lessening the risk that these are out of sync. The concept is explained in Chapter 3, Section 3.3, ‘ORM - Object Relational Mapping’ in more depth.
• A very flexible data-model. Because of the ORM and the MVC patterns, SilverStripe is able to consume quite complex data structures. You might have all sorts of different ‘types’ of pages, each with different fields. Then you might add products, members, product reviews, coupon codes, and all sorts of other objects to your website. All of this data needs to be stored in your database, managed in the CMS, and presented on your public website. SilverStripe allows you to have a complex entity model, full of relationships, while ensuring the structure and data granularity is elegant.
• HTML, CSS, and JavaScript. Being the lingua franca of the web, SilverStripe respects that competent website developers need to have control over and separate their website into these three languages. In other words: SilverStripe doesn’t make you add CSS into your HTML. Nor does it prevent you from intelligently using JavaScript to progressively enhance your website with extra functionality. It stays out of your hair - as a developer, you can craft these files and incorporate them into your project in an elegant fashion. This provides for fantastic flexibility in your markup, therefore providing freedom in visual design.
• Simple template language. The ‘View’ mentioned in the MVC explanation above means that SilverStripe templates don’t contain logic. More than simply insisting pedantically that the Controller instead should contain this logic - it means that the templates deliberately resemble standard HTML syntax and that they can be created and edited by people without PHP skills. This lets you unleash your zealous HTML- and CSS-skilled designer on SilverStripe templates. Compared to other templating languages, SilverStripe’s seems overly simplistic. But you might come to appreciate the benefit of this in the same way you appreciate extracting your CSS out of your HTML: When you need to change something you have only one place to look, making changes easy and encouraging consistency.
• Class inheritance as a means of customization. This is really a topic for a later chapter in the book. But it’s important, and so we whet your appetite with a preview. If you have the concept of a ‘Product’ in your application, how do you customize that to make some ‘Products’ a ‘Book’, which might require an Author field? Extensions like this are fundamental to any CMS software package. SilverStripe uses the natural capabilities of an object-oriented language to extend Products into Books. This is nothing special in any object-oriented language, and all MVC frameworks do this, but it’s rare for a CMS to get out of your way and just let you use these natural features of object-oriented code.
• Clean file system structure. SilverStripe’s file and folder structure is neatly organized in several ways. The core application lives in a couple of top-level folders. All your project-specific changes go into your own top-level folders, providing convenient separation from the core package. Files containing code are named specifically based on the PHP classes they define. This means a lot of files, but also makes the role of each file specific and deliberate. Template files follow similar naming conventions, which makes SilverStripe websites portable: You can just move files and folders from one installation to another and be confident about what functionality in the application you’re shifting.
• Modules, themes, and widgets. The core functionality of SilverStripe can be extended by modules (for example ‘forum’ functionality), themes (changing the visual appearance of your website), and widgets (small features you can add to a page). We will build all of these types throughout this book. Extensions allow the core to be kept compact and succinct, so you don’t have a product with features you don’t need. Although the ability to have fully-featured modules isn’t a surprise for a CMS, having them tightly integrated at a framework level is a unique characteristic.
• Automated tests. SilverStripe provides a neat structure for testing any custom code you write. This means that you can test that your application works, automatically (we talk about this a bit more in Chapter 9, ‘Testing’). Automated tests allow you to make a code-level change to your website and test that you’ve not broken other features in your website. This reduces the friction of making changes to your application. In turn, this translates to being more able to continuously update your application, which is very appropriate in the world of ‘continuous beta’, and supports an Agile development methodology (see the following box). By the way, SilverStripe uses automated tests to ensure the consistency of its core functionality as well.
Agile development
This term stands for a software development methodology that fosters a process of frequent inspection and adaption after an initial planning phase. It’s in contrast to a more rigid methodology, commonly known as Waterfall, where you devise a detailed specification upfront and proceed to build to that specification, generally with fixed budgets and timeframes.
The agile approach embraces the idea that it’s impossible to predict exactly what you want ahead of seeing your software take shape. Speaking metaphorically, it’s very difficult to foresee the impact of a picture in your living room based on the floor plan. Perhaps the lighting is totally different from what the window placement suggests?
Instead of resisting change requests, an agile approach involves constant communication, demonstrations, and changes, as well as re-prioritizing what should be worked on. Agile maintains this notion throughout the process: Your software should be working and ‘deliverable’ most of the time, as opposed to just being launched at the ‘eleventh hour’.
A major benefit of an agile approach is that you’re more likely to finish with a useful set of features - the features implemented are the most important ones. Done well, agile also serves to maintain project schedules and budgets.
Agile is a way of thinking that involves everyone in a project: It impacts project managers and stakeholders just as much as developers - and it requires discipline from each of them. Agile works best with software that can quickly prototype features and that can support change easily.
More information on agile methodologies is available athttp://agilemanifesto.org/andhttp://agilealliance.org.
1.1.4 Interoperability and Open Standards
SilverStripe makes substantial use of open and common technologies as first-class citizens. The choice of PHP, MySQL, HTML, CSS, and JavaScript for example is very deliberate: They score well in terms of being well understood by the web industry, are open rather than in the control of a private company, and therefore are likely to be supported for a long time into the future. Here are some specific examples of SilverStripe’s treatment of interoperability and open standards:
• Embracing browser compatibility. SilverStripe does a lot of work to ensure that your website and administration system hums along in different web browsers. We’ve already covered the main factor here: SilverStripe gives you full control of HTML and CSS in your templates. It’s an indictment on other CMS products that we even have to mention this: But yes, content authors using the SilverStripe backend can use a Mac, Windows, or Linux computer for their work because it performs well in Internet Explorer, Firefox, Safari, and Chrome. With all these browsers competing for supremacy, your website and CMS backend need to be cross-browser compatible now if they’re to have any hope of being cross-browser in the future. The core developers of SilverStripe also have a watchful eye on HTML 5, which is quickly gaining traction after a long period of stagnation in the HTML standard.
• JavaScript and progressive enhancement. Ideally a website should work with JavaScript disabled, thereby ensuring accessible functionality and content for both users and search engines. This paradigm has two approaches: graceful degradation and progressive enhancement. SilverStripe supports these for your frontend templates, both by giving you full control over the templates as explained earlier, and by ensuring that automatically generated markup complies with the principles of progressive enhancement. Although the CMS backend does require JavaScript to function, it shies away from excessive Javascript-generated HTML, making debugging easier, allowing the backend user interface HTML to be edited as template files, and encouraging robust customizations.
• Database Abstraction. SilverStripe currently only supports MySQL in a stable release, but the underlying architecture allows for other database drivers. Because of this, SilverStripe has been shown to work on other databases such as PostgreSQL or the Microsoft SQL server. Note that both are currently in an alpha state.
• Server-side interoperability. SilverStripe requires a PHP webserver but not much else. It supports running on the two most popular webservers, Apache and Microsoft IIS. Being able to install SilverStripe onto Windows, Mac, and Linux servers means that you can trial or deploy it on an architecture that you’re familiar with or that will better support integration into your IT environment.
• Accessibility. Having control over HTML, CSS, and JavaScript means that it’s easy to write the markup that validates against Web Content Accessibility Guidelines (WCAG) as published by the W3C (see http://www.w3.org/TR/WCAG20/), and therefore can be processed easily by screen readers. This is a necessity for government sector work, and in case the standard commercial justification is instead important to you: Good markup positively influences your search engine rank!
• Unicode. Not everybody has only 26 letters in their alphabet. New Zealanders typically need the Macron so that they can spell ‘Māori’. Europeans have various diacritics. The Chinese have tens of thousands of Han characters. The Unicode standard enables SilverStripe templates and the content entered into the CMS to be in multiple languages and alphabets.
• Supporting the ‘web of data’ and it’s APIs. There’s an inexorable trend away from websites only providing their content and features in a human-readable format. If your website catalogs a hundred books, or adds a dozen fresh news articles every day, this content shouldn’t just be accessible in a gleefully designed HTML and CSS webpage. The information should also be available to download as a CSV document. Or an RSS feed. Or better yet, a full Web Services API, allowing the content to be machine-readable in a robust and versatile fashion. This lets other websites and tools take information from its authoritative source - your website - and promote it elsewhere. However, you’re unlikely to bother with such a feature on your website if it adds time or complexity to your project. Fortunately, as Chapter 6, Section 6.10, ‘Web services using RESTfulServer’ explains, SilverStripe gives you robust and feature-rich APIs with very little code.
1.1.5 Conventions
As you might have begun to determine already, SilverStripe makes a lot of use of conventions. There are also documented PHP coding standards, conventions for HTML and CSS, and naming conventions for functions, methods, and filenames. As a result, you have a well-considered structure to follow for your projects - this allows teams of people to work on SilverStripe projects, and helps you share your work with others in the overall developer community.
Related to this is the principle of convention over configuration, which has two major benefits: Efficiency and robustness to the developer and user-friendliness to content authors, as illustrated by these examples:
• The base package ‘just works’ out-of-the-box. It provides a helpful installer, and immediately can be used to add pages and run a website. A default theme means that it’s feasible to write no code and have this as a public website - it would just look a little bland. Extension modules such as the blog and forum adhere to this ‘works out-of-the-box’ principle, too, which makes getting started with SilverStripe quicker.
• Options are only visible in the user interface where they’re commonly used. Functions with less frequent usage exist on the sidelines without cluttering up the interface, and rarely used functions are either possible through extension modules or may be excluded altogether. Those rare features might still be useful to you, and are basically waiting for a developer to write them using one of the many extension points in the framework. Although this may make you consider using an older, more ‘feature rich’ alternative to SilverStripe, do be careful: In general there’s a major switch toward using more lightweight tools that are user-friendly. A good CMS is one that doesn’t have a ton of functionality you never use.
• The same is true at the code level, in the Sapphire framework. The core package focuses on providing commonly needed features easily. Generally, if functionality is missing, it provides easy means for adding, replacing, or changing behavior - by writing code. This is in contrast to having a multitude of built-in options that serve to complicate and bloat the software. This focus is rare in CMS packages.
1.1.6 CMS Interface
So far we’ve discussed principles and architecture. They’re important to mention because they might not be as readily apparent as the functionality that’s visible within the CMS backend functions provided by the SilverStripe backend is to try it out. The best way to understand the functions provided by SilverStripe is to try it out, for instance the official public demo at http://demo.silverstripe.com/ or the screencast at http://silverstripe.org/assets/video/cms.html.
Chapter 4 serves to explain the CMS interface in detail, so we’ll just mention some interesting features here.
In comparison to other CMSs, the backend is quite clean and uncluttered, and supports intuitive usage without specialized knowledge. Long training sessions should be a thing of the past with SilverStripe for the average computer user who is familiar with using Microsoft Word or similar text processing solutions.
Behind the scenes, SilverStripe was an early adopter of highly interactive interfaces built around JavaScript and AJAX, which means certain areas of the interface can dynamically adapt to user actions without reloading the entire application. AJAX powers key tasks such as opening and saving pages, inserting images and links, and most strikingly, using drag&drop to organize your sitemap. The use of AJAX makes performing these standard tasks much quicker than the traditional approach of having to reload the entire webpage. Other interesting features include the following:
• A site-tree interface instantly provides users with the idea of the organization of the website’s pages, and how to edit and update pages.
• Each page has a private ‘draft’ view, which you can work on until you’re happy to publish it live. Each page version is saved, allowing you to revert to and compare older versions of pages.
• There’s support for websites having multiple languages and subsites.
• The user interface used by content authors is translated into many different languages, which makes it more accessible to non-English markets.
• There’s powerful and automatic image manipulation. If you insert a 10 megapixel image onto your homepage, SilverStripe automatically reduces it to a filesize appropriate for the web.
• The URLs are friendly URLs, of the format http://yoursite.com/pagename/.
• You can use a WYSIWYG editor to update content, sidestepping the need for content authors to learn HTML.
• There’s a graphical user interface to manage files and other documents, as well as security permissions.
• Some extension modules provide rich additional functionality to the CMS. For instance, the Userforms module lets non-technical people create forms for their website. The Workflow module provides the ability for larger groups of people to work on a website, ensuring that content goes through an approval process before being published.
• It’s highly customizable. Developers can substantially alter the user interface so that content authors have the ability to manage their unique website. This is much more than being able to add a custom field - you can create entirely new data management interfaces, making the CMS backend capable of managing all sorts of data.
1.1.7 Commercial Open Source Software - Best of Both Worlds?
SilverStripe is open source software, which means that you benefit from access to the source code, and of course that it’s free to use. It also serves to build a global community of developers who take interest in the software, sharing best practices, code, documentation, roadmap ideas, and so on.
The source code is managed and predominantly produced by a privately held company, SilverStripe Ltd. This in contrast to a community ownership model that often typifies open source. Despite SilverStripe being produced by a company, which would often suggest there being a ‘commercial’ and a ‘free community’ version, the SilverStripe company instead focuses on making a single (free) version great.
Having a company behind an open source project typically allows the best of both worlds: On the one hand it provides access to code, a good price, and minimizes lock-in to a vendor. On the other hand, it also provides assurance that there is a number you can call if you want to pay for professional services, such as resolving an issue or commissioning a feature. You can visit http://silverstripe.com/ for more detail on the professional services that SilverStripe and its partner companies offer, or keep an eye on the community forums on http://silverstripe.org/ for freelancers.
However, the devil is in the detail: Open source has become a coveted term and there’s variation in just how ‘open’ different ‘open source content management systems’ are. Some companies profess to provide open source software, but fail to honor some key principles beyond just providing access to the source code. In SilverStripe’s case, the company does the right thing and provides a number of attributes necessary for the open source litmus test:
• Source code is available in a public versioning repository. All past and upcoming versions of the software are available, with all changes between them shown in a convenient manner. Every change on every line of code can be tracked to a person, a moment in time, and a release.
• The project accepts (and encourages!) contributions in the form of code back to the project. Although nobody outside of the company has commit rights to the core package at the moment, contributed patches are regularly added to the core, and many members in the community have commit rights to extensions. So far, the company’s control appears to have done a good job prioritizing sound architecture and usability.
• Core developers regularly appear publicly on support forums and use a development mailing list to advise of the roadmap, and actively encourage discussion and input by the wider developer community. A healthy sign of this is that some features rise in the priority list of the core team after community discussion. Multiple language support is an example of an often requested feature that was implemented by SilverStripe based on community feedback.
• The bug tracker and feature request system are all publicly visible and open to the public to use at http://open.silverstripe.com/. A public roadmap and a real-time list of changes to the product are also found here.
• SilverStripe is distributed under the commonly used BSD license, which is a permissive license approved by the Open Source Initiative (http://opensource.org/). SilverStripe refrained from crafting their own open-source license, which means that your legal team will have an easier job reviewing the license details (assuming they know about open source!).
BSD license
BSD is short for Berkeley Software Distribution, which is a liberal license model originally developed by the American university of the same name. The BSD license allows copying, modifying, and distributing of software without having to grant access to the altered source code, and is by definition a ‘permissive’ license. The only requirement is that the original (fairly short) license note has to stay in place. The complete license can be found at http://opensource.org/licenses/bsd-license.php.
In practice, this means that service providers can develop specific extensions for paying customers without obligations to license this work as open source. The created intellectual property stays with the service provider.
SilverStripe is one of very few CMSs that take this liberal approach of BSD licensing. Most open source alternatives use a variant of the GNU Public License (GPL), which enforces greater responsibility around contributing your changes back into the core product.
1.1.8 What You Don’t Get
Another way to define something is by what it doesn’t have:
• There’s no graphical user interface to manage templates, website logic, alter your database schema, provide a ‘control panel’, and so forth. These are all managed by editing code at the framework level, offering more flexibility to developers.
• The template files and PHP files are stored on the file system. This means that the responsibility of maintaining a history of old versions of these files, allowing collaboration by multiple people editing these files, and pushing files from ‘development’ to ‘production’ is up for you to manage. There’s plenty of powerful tools to provide this facility (e.g., Subversion and Rsync) but SilverStripe doesn’t do it for you.
• SilverStripe is not a document management system, a term that normally refers to a more heavy-weight product capable of managing many thousands of documents for perhaps just as many staff, and robustly ensuring versioning, integrity, and security of the files. Any document management system worth its salt will have APIs to provide integration with SilverStripe, allowing for instance the uploading of files into the CMS from your document store. SilverStripe does have a powerful ‘Files and Images’ system that lets website content authors manage thousands of publicly accessible images and documents on your website, and it’s well suited to that purpose.
• You don’t get a Microsoft application with SilverStripe, but if want to want to leverage knowledge or investment in a Microsoft environment, take advantage of SilverStripe being able to run on IIS and talk to SQL Server databases. Use APIs if you need integrate with third party applications such as Sharepoint.
• There’s no inline editing. Some content management systems allow you to browse the website, find a section of content you want to edit, click it, and edit it right then and there - ‘inline’. SilverStripe has chosen to put more effort into making a ‘backend’ CMS interface polished and user-friendly. You’ll see in this book that forms can be added to the ‘frontend’, which update pages and content in the CMS, but these are focused on providing specific functions, such as letting members update their profile. However, you can have a link shown on webpages that loads the CMS backend for the current page.
• There’s not gazillions of modules, themes, widgets, translations, and developers able to give you free support ‘yesterday’. If you want something modern you need to be prepared to have less of these amenities. Bear in mind that you don’t need so much pre-built code because it should be easy to write it yourself.
• We don’t supply an application that runs on the x386 PC you have earmarked for the local museum. SilverStripe is built in an environment where dual-core machines are the lowest-end computers available. That’s not to say SilverStripe shouldn’t concentrate on client-side performance in the browser, but it makes pragmatic choices. On server-side performance, you can expect several page views to be dynamically generated per second; hundreds if you use static caching.
1.2 History
After giving you a high level overview of what SilverStripe has in store technically, we’d like to give you a little insight into where it comes from. Welcome to our little SilverStripe history lesson!
The website development company SilverStripe Ltd was founded in 2000 in the beautiful capital of New Zealand, Wellington. The three founders Tim Copeland, Sam Minnée, and Sigurd Magnusson originally developed and marketed a closed-source PHP4-based CMS to local small and medium-sized business customers.
In 2005, the business decided to rebuild this CMS from scratch in PHP5, using the experience gathered throughout five years of commercial CMS development. This rewrite was largely motivated by the need to support larger customers with more complex website requirements. The rewrite came with a twist, too: This time it would be open sourced. SilverStripe hoped to foster goodwill and a wider adoption by this move, assuming it would make SilverStripe a better and more mature product in the long run. If they could pull it off and create a thriving community around the newcomer, the feedback and ideas generated would mean welcome improvements to the overall system.
The software was rewritten substantially in 2006, with beta downloads available late that year, and v2.0.0 stable released in February 2007. Just months after the stable release, the project was accepted into the GoogleSummer of Code, followed shortly later that year by being accepted into the Google Highly Open Participation Contest (see later box ‘Google’s open source initiatives’).
These two programs brought SilverStripe to the attention of web developers around the world, and led to many new features being contributed to the software. In 2008, the software won ‘Most Promising CMS’ at the PacktPub Open SourceCMS awards, having been a finalist the year before. The software also featured at the annual MySQL Conference in California, won at the New Zealand Open Source Awards, and was used to power http://demconvention.com/, a high traffic official website in the recent and very visible US Presidential Elections.
In 2009, the software was chosen as one of ten packages bundled with Microsoft Web Platform Installer, an automated way to install PHP applications on Microsoft’s IIS webserver. The Microsoft installer now accounts for nearly half of SilverStripe’s downloads each month. Since launch, the SilverStripe project team have maintained at least one major and a couple of minor releases each year.
On the commercial side, the SilverStripe company has more than tripled its company size since going open source, currently employing over 30 staff. To help grow the company, in 2007 the founders appointed a new CEO, Brian Calhoun, who had spent considerable time working in the Silicon Valley software industry.
All employed developers can dedicate a certain percentage of their work time to open source development. Many new features also find their beginnings in commercial work for specific clients with enough foresight to allow open source usage of their commissioned work. Much of the company’s work has come from international clients who became aware of the open source product without any significant marketing effort on behalf of SilverStripe, by virtue of the community spreading the word.
Google’s Open Source Initiatives
Through the Google Summer of Code (GSOC) and Google Highly Open Participation (GHOP) Contest programs, the search giant shows generous support for open source software. Both programs encourage students to contribute to established open source projects.
The Summer of Code is a reference to the Summer of Love that took place in San Francisco, 1967 - and implies similarly youthful and revolutionary energies. The annual event began in 2005, and provides hundreds of paid internships to university students. The students work for about three months over the northern hemisphere summer, and are mentored by members of an open source project to contribute a specific feature or effort to that project. More information is available at http://code.google.com/soc/.
The Google Highly Open Participation Contest connects high-school students with open source projects in a similar fashion, but with paid tasks that take only hours, not months, to complete. Further information is at http://code.google.com/ghop/.