milesj / utility

[Deprecated] A CakePHP plugin for common utility classes.
MIT License
69 stars 24 forks source link

slugExists #22

Closed FrodeMMeling closed 10 years ago

FrodeMMeling commented 10 years ago

The Sluggable behavior should have an exists method like CakeModel has for id. This will make it easier to convert scaffolded code to slug.

Here is a function that works (simplified version of CakeModel::exists)

    public function slugExists($slug = false) {
        if ($slug === false) {
            return false;
        }

        return (bool)$this->find('count', array(
            'conditions' => array(
                $this->alias . '.' . 'slug' => $slug
            ),
            'recursive' => -1,
            'callbacks' => false
        ));
    }

you can then in view action write:

    public function view($slug = null) {
        if (!$this->Asset->slugExists($slug)) {
            throw new NotFoundException(__('Invalid asset'));
        }
        $options = array('conditions' => array('Asset.' . 'slug' => $slug));
        $this->set('asset', $this->Asset->find('first', $options));
    }
milesj commented 10 years ago

You could just use $this->Asset->findBySlug($slug) in this case.

FrodeMMeling commented 10 years ago

Yes, i know, but I think the find count is much faster when you have large amount of records.

milesj commented 10 years ago

Added.