Successfully reported this slideshow.
Your SlideShare is downloading. ×

Abstracting functionality with centralised content

Upcoming SlideShare
Html5, a gentle introduction
Html5, a gentle introduction
Loading in …3

Check these out next

1 of 60 Ad

More Related Content

Slideshows for you (20)


Similar to Abstracting functionality with centralised content (20)

More from Michael Peacock (20)


Abstracting functionality with centralised content

  1. 1. Abstracting functionality with Centralised Content<br />Michael Peacock<br />
  2. 2. About me<br />Senior Web Developer<br />M.D. of design agency Peacock Carter<br />Technical director for an online retailer<br />Author<br /><br /><br />@michaelpeacock<br />
  3. 3. What's in store?<br />Setting the scene – a look at the problem centralised content solves<br />Centralised content – what is it and how can it solve this problem<br />Implementation – How we implemented centralised content with PHP and MySQL<br />
  4. 4. A sample bespoke CMS / basic e-commerce website<br />Pages<br />Blog entries<br />Blog categories<br />News articles<br />Products<br />Product Categories<br />Events<br />Users can buy products<br />Users can rate products<br />Users can comment on / review products<br />Users can comment on blog entries<br />
  5. 5. Commenting<br />Needed for both blog entries and products<br />Create a simple library or function to create a comment for us<br />Comments table in our database<br />Table to link them to blog entries<br />Table to link them to products<br />
  6. 6. Database<br />
  7. 7. What about searching<br />Do we have search boxes for different aspects of the site?<br />Do we use a complex searching system?<br />Should we just let Google do it for us?<br />“Can’t someone else do it?” Homer J Simpson<br />
  8. 8. What if in the future, once development is complete…<br />Users need to be able to rate blog entries<br />Users need to be able to purchase (book onto) events<br />… and comment on them<br />… … and rate them…<br />Sounds like a pain!<br />
  9. 9. Let’s take a step back…<br />And centralise our content!<br />
  10. 10. Centralised Content<br />Useful architecture; especially for CMS projects<br />MVC brings out the best in it<br />Drupal<br />“node”<br />MVC would be nice, Drupal<br />Used extensively in our own CMS and frameworks for the past year and a half;<br />
  11. 11. Content<br />Typical content found on a CMS powered site:<br />Pages<br />Blog entries<br />News articles<br />Job vacancies<br />Products<br />Events<br />Photographs / Image gallery<br />
  12. 12. Pages<br />Name<br />Heading<br />Page content<br />Meta data / title<br />URL<br />
  13. 13. Blog Entries<br />Name<br />Heading<br />Blog entry<br />Meta data / title<br />Leading image<br />Leading paragraph<br />Author<br />URL<br />
  14. 14. News articles<br />Name<br />Heading<br />News article<br />Meta data / title<br />Leading image<br />Leading paragraph<br />Author<br />URL<br />
  15. 15. Job Vacancies<br />Name<br />Heading<br />Job description<br />Location<br />Application deadline<br />Salary<br />Meta data / title<br />Author<br />URL<br />
  16. 16. Products<br />Name<br />Heading<br />Product description<br />Price<br />Weight<br />Image<br />Meta data / title<br />Author<br />URL<br />
  17. 17. Events<br />Name<br />Heading<br />Event description<br />Location<br />Date<br />Start / End time<br />Meta data / title<br />Author<br />URL<br />
  18. 18. Gallery Images<br />Name<br />Heading<br />Image caption / description<br />Camera data<br />Location<br />Image location<br />Meta data / title<br />Author<br />URL<br />
  19. 19. Its all the same! (well, almost…)<br />Name<br />Heading<br />Title<br />URL / Path / Search Engine friendly name<br />Primary content / description / details<br />Meta data<br />Creator / Author <br />Active / Enabled<br />Comments enabled / disabled<br />
  20. 20. …with extra bits depending on the type<br />Products<br />Price; Stock level; SKU; Weight<br />Events<br />Venue; Spaces; Price; Date; Start time; End time<br />Gallery image<br />Image file location; Camera details; Location<br />Job vacancy<br />Salary; Location; Start date; Type; Application date<br />
  21. 21. Content versions<br />With content being centralised we can implement versioning more easily<br />Record all versions of content<br />Static content IDs which relate to the active version<br />
  22. 22. So; let’s centralise it!<br />Core fields will make up our main table of content (content_versions)<br />Content types will have their own table, containing type specific fields content_versions_*<br />A content table (content) will store static data, such as author, creation date, ID, and reference the current active version certain toggle-able fields (active, commentable) should go here<br />Regardless of the version in play, the content ID can be used to access the element, and won’t change.<br />
  23. 23. Core database<br />
  24. 24. Within MVC<br />Content model<br />Models for each content type, extending the content model<br />For administrative tasks (CMS) content controller to perform shared operations: toggle active, toggle comments, delete<br />Content type controllers extend<br />
  25. 25. Content model<br />Deals exclusively with content and content versions tables<br />Getters and setters for core content fields<br />Creating content:<br />Create new content version<br />Create new content record, pointing to the version<br />Editing content<br />Create new content version<br />Log the old version ID in a versions log<br />Update the content record to point to the new version<br />
  26. 26. Content: save<br />public function save()<br />{<br /> // are we creating a new content item?<br /> if( $this->id == 0 )<br /> {<br />/** create the content versions record */<br /> $this->registry->getObject('db')->insertRecords( 'content_versions', $insert );<br />// record the ID<br /> $this->revisionID = $this->registry->getObject('db')->lastInsertID();<br />/** insert the content record */<br /> $this->registry->getObject('db')->insertRecords( 'content', $insert );<br />// record the ID<br /> $this->id = $this->registry->getObject('db')->lastInsertID();<br /> }<br /> else<br /> {<br />// have we changed the revision, or just something from the content table?<br /> if( $this->revisionChanged == true )<br /> {<br />// make a note of the old revision ID for the history<br /> $this->oldRevisionID = $this->revisionID;<br />/** insert the new content_versions record */<br /> $this->registry->getObject('db')->insertRecords( 'content_versions', $insert );<br />// update the revisionID<br /> $this->revisionID = $this->registry->getObject('db')->lastInsertID();<br />/** record the history */<br /> $this->registry->getObject('db')->insertRecords( 'content_versions_history', $insert);<br /> }<br />/* update the content table */<br /> $this->registry->getObject('db')->updateRecords('content', $update, 'ID=' . $this->id );<br /> }<br />}<br />
  27. 27. Product (i.e. a content type) model<br />Extends content model<br />Getters and setters for extended data for the content type<br />Creating product<br />
  28. 28. Product: save<br />public function save()<br />{<br />// Creating a new product<br /> if( $this->getID() == 0 )<br /> {<br />parent::setType( $this->typeID );<br /> parent::save();<br /> $this->saveProduct();<br /> }<br /> else<br /> {<br /> // tells the parent, that the revision has changed, <br /> // i.e. that we didn't just toggle active / change something from the _content_table!<br />$this->setRevisionChanged( true );<br /> parent::save();<br /> $this->saveProduct();<br /> }<br />}<br />
  29. 29. Product: Saving product data<br />private function saveProduct()<br />{<br />/** insert product specific data */<br /> // product version ID should be the same as the content version ID for easy maping<br /> $insert['version_id'] = $this->getRevisionID();<br /> $this->registry->getObject('db')->insertRecords( 'content_versions_store_products', $insert );<br /> // get the content ID<br /> $pid = $this->getID();<br /> // categories<br /> // delete all associations with this product ID<br /> // insert new ones based off user input; $pid to reference product<br /> // shipping costs<br /> // delete all associations with this ID<br /> // insert new ones based off user input; $pid to reference product<br />}<br />
  30. 30. A load of CRUD!<br />Creating<br />New features / content types we only need to code for the extended fields<br />Reading<br /> Custom constructor in the child model<br />Call setters for content type specific fields<br />Call parent setters for core content<br />Child method to iterate through / process fields to go to the template engine<br />
  31. 31. A load of CRUD!<br />Updating<br />Parent deals with all the core fields (no new work!)<br />Insert (versions) extended fields<br />Use the ID the parent gives to the content version, to make table mapping easier<br />Deleting<br />Assuming “deleting” just hides content from front and back-end<br />Parent object updates content record to deleted – no extra work!<br />
  32. 32. Commenting<br />Requires just one database table<br />Can be used, without additional work, for all content types<br />Each comment relates to a record in the content table<br />
  33. 33. ... commenting<br />private function postComment( $id )<br />{<br />require_once( FRAMEWORK_PATH . 'models/comment/comment.php');<br /> $comment = new Commentmodel( $this->registry, 0 );<br /> // tell the comment which content element it relates to<br /> $comment->setContent( $id );<br /> $comment->setName( isset( $_POST['comment_name'] ) ? $_POST['comment_name']: '' );<br /> $comment->setEmail( isset( $_POST['comment_email'] ) ? $_POST['comment_email']: '' );<br /> $comment->setURL( isset( $_POST['comment_url'] ) ? $_POST['comment_url']: '' );<br /> $comment->setComment( isset( $_POST['comment_comment'] ) ? $_POST['comment_comment']: '' );<br /> $comment->setIPAddress( $_SERVER['REMOTE_ADDR'] );<br /> $comment->setCommentsAutoPublished( $this->registry->getSetting('blog.comments_approved') );<br /> $comment->setPageURL( $this->registry->getURLBits() );<br /> if( $comment->checkForErrors() )<br /> {<br /> /** error processing */<br /> }<br /> else<br /> {<br /> // save the post<br /> $comment->save();<br />/** Redirect to the controller the user was on before, based on the URL */<br /> }<br />}<br />
  34. 34. Rating<br />Again, just one table<br />Directly relates to the appropriate content element<br />Create it once; works for all content types – no future work for new content types<br />
  35. 35. Geo-tagging<br />Either extend the content / versions tableOR<br />Create a co-ordinates table and map it to the content table<br />
  36. 36. What else?<br />Keyword tagging<br />Keywords table<br />Content keywords associations table<br />Central functionality to add keywords and delete orphaned keywords<br />Categories<br />A content type (up for debate) – why?<br />New table to map content to content<br />Central functionality to manage associations<br />
  37. 37. Purchasing<br />Provided content types have consistent cost / shipping fields, they can slot into the order pipeline<br />Won’t work for all content types<br />Makes conversion easy<br />Make event purchasable?<br />Make gallery image purchasable?<br />Just add price fields, and indicate the content type can be purchased<br />
  38. 38. Purchasing<br />By giving an image a price field, pre-existing e-commerce functionality can process it<br />Piece of cake<br />
  39. 39. Hierarchies and ordering<br />Ordering pages within the sites menu<br />Moving pages within another page<br />Ordering product categories<br />Ordering blog entries<br />Ordering news articles<br />
  40. 40. Searching<br />Search the content & content versions table<br />LEFT JOIN content_versions_* tables where appropriate<br />Designate searchable fields<br />Execute the query<br />Enjoy integrated search results!<br />
  41. 41. Searching: Define our extended search fields<br />private $extendedTablesAndFields = array( <br /> 'content_versions_news' => array( 'joinfield' => 'version_id', 'fields' => array( 'lead_paragraph' ) ) <br />);<br />
  42. 42. Searching: Build our left joins<br />$joins = "";<br />$selects = "";<br />$wheres = " ";<br />$priority = 4;<br />$orders = "";<br />foreach( $this->extendedTablesAndFields as $table => $data )<br />{<br /> $field = $data['joinfield'];<br /> $joins .= " LEFT JOIN {$table} ON content.current_revision={$table}.{$field} "; <br />foreach( $data['fields'] as $field )<br /> {<br /> $wheres .= " IF( {$table}.{$field} LIKE '%{$phrase}%', 0, 1 ) <> 1 OR ";<br /> $selects .= ", IF( {$table}.{$field} LIKE '%{$phrase}%', 0, 1 ) as priority{$priority} ";<br /> $orders .= " priority{$priority} ASC, ";<br /> $priority++;<br /> }<br />}<br />
  43. 43. Searching: Query!<br />$sql = "SELECT *, <br /> IF(content_types.reference='page',content.path,CONCAT(content_types.view_path,'/',content.path ) ) as access_path, <br /> REPLACE(substr(content_versions.content,1,100),'<p>','') as snippet, <br /> as ct, <br /> IF( LIKE '%{$phrase}%', 0, 1 ) as priority0, <br /> IF( content_versions.title LIKE '%{$phrase}%', 0, 1 ) as priority1, <br /> IF( content_versions.heading LIKE '%{$phrase}%', 0, 1 ) as priority2, <br /> IF( content_versions.content LIKE '%{$phrase}%', 0, 1 ) as priority3 <br />{$selects} <br />FROM <br /> content <br /> LEFT JOIN <br />content_types ON content.type=content_types.ID<br />{$joins} <br /> LEFT JOIN <br />content_versions ON content.current_revision=content_versions.ID <br />WHERE <br /> AND <br />content.deleted=0 AND <br /> ( IF( LIKE '%{$phrase}%', 0, 1 ) <> 1 OR <br /> IF( content_versions.title LIKE '%{$phrase}%', 0, 1 ) <> 1 OR <br /> IF( content_versions.heading LIKE '%{$phrase}%', 0, 1 ) <> 1 OR <br /> IF( content_versions.content LIKE '%{$phrase}%', 0, 1 ) <> 1 OR<br />{$wheres} <br /> ) <br />ORDER BY <br /> priority0 ASC, <br /> priority1 ASC, <br /> priority2 ASC, <br /> priority3 ASC, <br />{$orders} 1";<br />
  44. 44. Searching: Results<br />
  45. 45. Simple access permissions<br />public function isAuthorised( $user )<br />{<br /> if( $this->requireAuthorisation == false )<br /> {<br /> return true;<br /> }<br />elseif( $user->loggedIn == false )<br /> {<br /> return false;<br /> }<br />elseif( count( array_intersect( $this->authorisedGroups, $user->groups ) ) > 0 )<br /> {<br /> return true;<br /> }<br /> else<br /> {<br /> return false;<br /> }<br />}<br />
  46. 46. (Simple) Access permissions<br />Single table mapping content to groups<br />At content level, for content elements which require – cross reference the users groups with allowed groups<br />
  47. 47. Downloads / Files / Resources<br />Create them as a content type<br />Searchable based off name / description<br />Store the file outside of the web root<br />Make use of access permissions already implemented<br />Make them purchasable<br />
  48. 48. Not just “content”!<br />Other entities within an application which are similar<br />Social Networks<br />CRM’s<br />
  49. 49. Social Networks: Statuses<br />Core table: status<br />Creator<br />Profile status posted on (use it for both statuses and “wall posts”<br />The status<br />Creation date<br />
  50. 50. Social Networks: Statuses<br />Extended tables:<br />Videos: YouTube Video URL<br />Images: URL, Dimensions<br />Links: URL, Title<br />
  51. 51. ... Build a stream<br />Status streams<br />Recent activity<br />Viewing a profile’s “wall posts”<br />
  52. 52. Query the stream<br />Part of a stream model<br />SELECT <br />t.type_reference, t.type_name, s.*, <br /> as poster_name, as profile_name<br />FROM <br /> statuses s, status_types t, profile p, profile r <br />WHERE <br /> t.ID=s.type AND p.user_id=s.poster AND r.user_id=s.profileAND <br /> ( p.user_id={$user} <br /> OR r.user_id={$user} <br /> OR ( p.user_id IN ({$network}) AND r.user_id IN ({$network}) ) <br /> )<br />ORDER BY <br /> s.ID DESC LIMIT {$offset}, 20<br />
  53. 53. Generate the stream<br />For each stream record<br />Include a template related to:<br />the stream item type, e.g. video<br />The context, e.g. Posting on your own profile<br />Insert stream record details into that instance of the template bit<br />
  54. 54. foreach( $streamdata as $data )<br />{ <br /> if( $userUpdatingOwnStatus )<br /> {<br /> // updates to users "wall" by themselves<br /> $template->addBit( 'stream/types/' . $data['type_reference'] . '-me-2-me.tpl.php', $data );<br /> }<br />elseif( $statusesToMe )<br /> {<br /> // updates to users "wall" by someone<br /> $template->addBit( 'stream/types/' . $data['type_reference'] . '-2me.tpl.php', $datatags ); <br /> }<br />elseif( $statusesFromMe )<br /> {<br /> // statuses by user on someone elses wall<br /> $template->addBit( 'stream/types/' . $data['type_reference'] . '-fromme.tpl.php', $datatags ); <br /> }<br /> else<br /> {<br /> // friends posting on another friends wall<br /> $template->addBit( 'stream/types/' . $data['type_reference'] . '-f2f.tpl.php', $datatags ); <br /> }<br />}<br />
  55. 55. CRM’s<br />People and organisations are very similar<br />Centralise them!<br />Entity<br />Entity_Organisation<br />Entity_Person<br />Record Person <-> organisation relationships in a table mapping entity table onto itself<br />
  56. 56. Extending: Adding new content types<br />Drop in a model<br />Getters and setters for extended fields<br />Save method to insert extended data<br />Drop in an administrator controller<br />Rely on parent for standard operations<br />Pass CRUD requests / data to the model<br />Drop in a front end controller<br />Viewing: over-ride parent method & extend the select query<br />Anything else: Add specific functionality here<br />
  57. 57. Why centralise your content / common entities?<br />Eases content versioning<br />Write functionality (commenting, rating, etc) once, and it works for all current and future content types – without the need for additional work<br />Fixing bugs with abstracted features, fixes it for all aspects which use that feature<br />Conversion is relatively easy – e.g. Turn a page into a blog entry. More so if they don’t extend the core table<br />
  58. 58. Some of the problems<br />Can be a risk of content and content versions tables having too many fields<br />Optimization bottle-neck – poorly performing and optimizing tables will cripple the entire site<br />Versioning: Stores lots of data<br />Sometimes you want functionality to differ across features (e.g. Product reviews <> comments)<br />A bug in an abstract feature will be present in all aspects which use it<br />
  59. 59. phpMyAdmin is harder<br />Managing content via phpMyAdmin is more difficult<br />MySQL Views can help with listing and viewing content <br />
  60. 60. Thanks for listening<br /><br /><br />@michaelpeacock<br /> Please leave feedback!<br />