简体   繁体   中英

Phalcon PHP - how to custom Route to make url friendly like wordpress

I want to make my url friendly like:

http://abc.com/I-want-to-make-my-url-friendly-like

and

http://abc.com/my-category/I-want-to-make-my-url-friendly-like

in Phalcon.

Thank you very much.

You can use conversions on your routes that rely on a custom function

// The action name allows dashes, 
// an action can be: /products/new-ipod-nano-4-generation
$router
  ->add(
    '/{category:[[a-z\-]+]/{slug:[a-z\-]+}', 
    array(
        'controller' => 'products', // This can be any controller you want
        'action'     => 'show' // Same here
    )
  )
  ->convert(
    'slug', 
    function ($slug) {
        return str_replace('-', '', $slug);
    }
  )
  ->convert(
    'category', 
    function ($category) {
        return str_replace('-', '', $category);
    }
  );

Thank Nikolaos Dimopoulos, your response means that you convert slugs to valid functions. I found out an answer for my question (with 3 levels category in my project):

   // Category
   $router->add(
        '/[a-z0-9-]{3,}/',
        array(
            'controller' => 'category',
            'action'     => 'index'
        )
    );
    $router->add(
        '/[a-z0-9-]{3,}/[a-z0-9-]{3,}/',
        array(
            'controller' => 'category',
            'action'     => 'index'
        )
    );
    $router->add(
        '/[a-z0-9-]{3,}/[a-z0-9-]{3,}/[a-z0-9-]{3,}/',
        array(
            'controller' => 'category',
            'action'     => 'index'
        )
    );

    // Static post
    $router->add(
        '/[a-z0-9-]{3,}',
        array(
            'controller' => 'post',
            'action'     => 'view',
            'slug'       => 1
        )
    );  

    // Product
    $router->add(
        '/[a-z0-9-]{3,}/([a-z0-9-]{3,})',
        array(
            'controller' => 'product',
            'action'     => 'view',
            'slug'       => 1
        )
    );
    $router->add(
        '/[a-z0-9-]{3,}/[a-z0-9-]{3,}/([a-z0-9-]{3,})',
        array(
            'controller' => 'product',
            'action'     => 'view',
            'slug'       => 1
        )
    );
    $router->add(
        '/[a-z0-9-]{3,}/[a-z0-9-]{3,}/[a-z0-9-]{3,}/([a-z0-9-]{3,})',
        array(
            'controller' => 'product',
            'action'     => 'view',
            'slug'       => 1
        )
    ); 

If anyone can optimize this, please post as another answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM