A slug is a term usually describing a uri-friendly version of a property of a data object.
In this case, the name field. What this observer does is, it takes whatever you have in your name field and creates a unique slug, to be used in uris and saves it in the slug field. e.g.:
Name: "Your mum's a slug"
Slug: "your-mums-a-slug"
If "your-mums-a-slug" exists, it will be "your-mums-a-slug-1"
<?php /** * Slug observer gives you the hability of auto add * unique slugs based on the passed properties. * * @author Isern Palaus ipalaus@ipalaus.es * @license MIT License * @copyright 2011 Isern Palaus * @link [url=http://ipalaus.es]http://ipalaus.es[/url] */ class Observer_Slug extends \Orm\Observer { public static $property = 'slug'; public static $from = 'name'; public function before_insert($obj) { $obj->{static::$property} = self::unique_slug($obj->{static::$from}, $obj::table()); } public static function unique_slug($name, $table) { $slug = \Inflector::friendly_title($name); $titles = array(); $query = \DB::query("SELECT slug FROM $table WHERE slug RLIKE '(".$slug.")(-[0-9]+)?$'")->execute(); if(count($query) > 0) { foreach($query->as_array() as $item) { $titles[] = $item["slug"]; } } $total = count($titles); $last = end($titles); /** * No equal results, return $slug */ if($total == 0) return $slug; /** * If we have only one result, we look if it has a number at the end */ elseif($total == 1) { /** * Take the only value of the array, because there is only 1 */ $exists = $titles[0]; /** * Kill the slug and see what happens */ $exists = str_replace($slug, "", $exists); /** * If there is no light about, there was no number at the end. * We added it now */ if("" == trim($exists)) return $slug."-1"; /** * If not.......... */ else { /** * Obtain the number because of REGEX it will be there... ;-) */ $number = str_replace("-", "", $exists); /** * Number plus one. */ $number++; return $slug."-".$number; } } /** * If there is more than one result, we need the last one */ else { /** * Last value */ $exists = $last; /** * Delete the actual slug and see what happens */ $exists = str_replace($slug, "", $exists); /** * Obtain the number, easy. */ $number = str_replace("-", "", $exists); /** * Increment number +1 */ $number++; return $slug."-".$number; } } }
<?php class Model_Test extends \Orm\Model { protected static $_observers = array( 'Slug' => array('before_insert'), '\Orm\Observer_CreatedAt' => array('before_insert'), '\Orm\Observer_UpdatedAt' => array('before_save'), ); }
It looks like you're new here. If you want to get involved, click one of these buttons!