pcsimpleslugbehavior Simple behavior to create slugs and parse URLs that expect those slugs to get the unique id for model

  1. Installation
  2. Usage
  3. Resources
  4. Change Log

This is a simple behavior component.


Unpack the package and place at /protected/components


In the model where you'd want to use, declare this behavior via its behvaiors() method, as follows:

public function behaviors() {
  return array(
    'slugmaker' => array(
      'class' => 'PcSimpleSlugBehavior',
      // 'sourceIdAttr' => the 'id' attribute name in this model. Default value = 'id'
      // 'sourceStringPrepareMethod' => If defined, will be used to get the base slug string text. Use it if you need some small manipulation of data in the model object in order to 'get' the base slug string. For example, if you need to concatenate 'first_name' and 'last_name' fields together.
      // 'sourceStringAttr' => the 'main string attribute' from which the slug will be built. Typically 'title', which is the default as well.
      // 'maxChars' => Maximum allowed slug total length. resulted slug will be trimmed to this value if longer than this value (*with* the prepended 'id-'...)
      // 'avoidIdPrefixing' => Setting this to true (default = false) will enable you to generate and parse URLs without the ID of the model record. WARNING: you need to carefully think before choosing this method as if not well thought, it could be used in an environment where there could be two or more records with same slug! 

Then, in the code you can do as follows:

// the following will generat the slug for you:
// get id of article from slug
$dummy = MyModel::model();
$id = $dummy->getIdFromSlug($slug_fetched_from_url);
$my_model_obj = MyModel::model()->findByPk($id);


Change Log

  • v1.6 20 March 2012: Added support for 'id-less' slugs. Use with caution! (see comment above)
  • v1.5 20 March 2012: Please ignore this version.
  • v1.4 16 Aug 2012: bug fix: fixed support for 'base slug generation' (in model class).
  • v1.3 12 Aug 2012: Added attribute sourceStringPrepareMethod. See documentation above on how to use it.
  • v1.2 7 Aug 2012:
    • added createBaseSlug() which is good for creating non-primary-key related slugs. For example, if you want to slug'ify a parameter in the middle of the URL.
    • Fixed the lower-casing to handle all strings as UTF8 - mb_strtolower() on an string that contains umlaut within created a bug...
  • v1.1 17 July 2012: Added 'lowercaseUrl' option that will makes the created slug all lowercase (MB safe).