i have url like this :
http://quickstart.local/public/category1/product2
and in url (category1/product2) numbers are id , categorys and products fetched from database attention to the id
id is unique
i need to the sensitive url like zend framework url. for example :http://stackoverflow.com/questions/621380/seo-url-structure
how i can convert that url to the new url like this
is there any way?!!
You'll need to store a unique value in your database with a field name such as 'url' or something similar. Every time you generate a new product you will have to create this unique url and store it with the product information. A common way to do this is to take the name of the product and make it url friendly:
public function generateUrl($name)
{
$alias = str_replace(' ', '-', strtolower(trim($name)));
return preg_replace('/[^A-Za-z0-9-]/', '', $alias);
}
Calling this method:
$url = $this->generateUrl("My amazing product!");
echo $url;
will output:
my-amazing-product
You'll need to check that the output from this function does not already exist in the database as you will use this value to query on instead of the id.
If you apply this logic to the categories as well, you can have easily readable and descriptive urls like the one below. You may need to tweak your routing before this works correctly though.
http://quickstart.local/public/awesome-stuff/my-amazing-product
You could use ZF's Zend_Controller_Router_Route. For example, to make similar url to those used by SO, one could define a custom route in an application.ini as follows (assuming you have controller and action called questions and show respectively):
resources.router.routes.questions.route = '/questions/:id/:title'
resources.router.routes.questions.type = "Zend_Controller_Router_Route"
resources.router.routes.questions.defaults.module = default
resources.router.routes.questions.defaults.controller = questions
resources.router.routes.questions.defaults.action = show
resources.router.routes.questions.defaults.id =
resources.router.routes.questions.defaults.title =
resources.router.routes.questions.reqs.id = "\d+"
Having such a route, in your views you could generate an url as follows:
<?php echo $this->url(array('id'=>621380,'title' => 'seo url structure'),'questions');
// results in: /myapp/public/questions/621380/seo+url+structure
//OR if you really want to have dashes in your title:
<?php echo $this->url(array('id'=>621380,'title' => preg_replace('/\s+/','-','seo url structure'),'questions');
// results in: /myapp/public/questions/621380/seo-url-structure
Note that /myapp/public/ is in the url generated because I don't have virtual hosts setup on my localhost nor any modifications of .htaccess made. Also note that you don't need to have unique :title, because your real id is in :id variable.
As a side note, if you wanted to make it slightly more user friendly, it would be better to have your url as /question/621380/see-url-structure rather than /questions/621380/see-url-structure. This is because under this url you would have only one question, not many questions. This could be simply done by changing the route to the following resources.router.routes.questions.route = '/question/:id/:title'.
EDIT:
And what to do with categories and products that you have in your question? So, I would define a custom route, but this time using Zend_Controller_Router_Route_Regex:
resources.router.routes.questions.route = '/questions/(\d+)-(d+)/(\w*)'
resources.router.routes.questions.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.questions.defaults.module = default
resources.router.routes.questions.defaults.controller = questions
resources.router.routes.questions.defaults.action = show
resources.router.routes.questions.map.1 = category
resources.router.routes.questions.map.2 = product
resources.router.routes.questions.map.3 = title
resources.router.routes.questions.reverse = "questions/%d-%d/%s"
The url for this route would be then generated:
<?php echo $this->url(array('category' => 6213,'product' => 80,'title' => preg_replace('/\s+/', '-', 'seo url structure')),'questions' ); ?>
// results in: /myapp/public/questions/6213-80/seo-url-structure
Hope this will help or at least point you in the right direction.
Related
I would like to create porfolio module, but I need it to be seo friendly, so url should look like:
example.com/portfolio/projectid
where portfolio - module, so it will be index action
projectid - based on field alias
its easy to create example.com/portfolio but how to create controller, or detect what is after?
The same URL hierarchy is in products, so it's category/product
Anybody have idea how to do it?
Below code works for item/id. you can change with your requirement.
$model = Mage::getModel('items/items');
/*Rewrite */
$isSystem = 0; // set 0 for custom url as we have created custom for profile extension
$_itemId = $model->getModuleItemId();//module_item_id field
$_itemName = $model->getTitle();//title field
$_itemName = strtolower(str_replace(" ", "", $_itemName));
// save profile view url rewrite
$viewIdPath = 'item/id'.'/'.$_itemId;
$viewRequestPath = 'items/'.$_itemName;
$viewTargetPath = 'items/index/item/id/'.$_itemId;//controller is itemsController.php, Action is itemAction()
$_coreUrlRewrite = Mage::getModel('core/url_rewrite');
$_coreUrlRewrite->load($viewIdPath, 'id_path'); // check if item path already saved? If yes, $_coreUrlRewrite will contain existing data.
$_coreUrlRewrite->setStoreId($_storeId)
->setIdPath($viewIdPath)
->setRequestPath($viewRequestPath)
->setTargetPath($viewTargetPath)
->setIsSystem($isSystem)
->save();
if(isset($viewRequestPath)){
$model->setUrl($viewRequestPath);
$model->save();
}
/*Rewrite End*/
You can find more info here & here
I have been spending quiet some time figuring out how this works - so thought lets ask the question here.
I do understand how to customize URL's in Joomla with the help of router.php - at least I thought so. It is simple to create something like this
domain.com/country/id
example:
domain.com/germany/12
However, you wouldn't know that the id stands for a city. So in this example lets assume the city with id 12 is Berlin.
So for my custom component (named: countries) I would like that the following is displayed:
for view=countries (1st level)
domain.com/country
i.e.:
domain.com/germany
for view=city (2nd level)
domain.com/country/city-id
i.e.:
domain.com/country/berlin-12
(or perhaps just: domain.com/country/berlin - but I think the ID is required for the custom component to work - and any related modules on the page that read the ID to know what to do)
What do I have so far:
function CountriesBuildRoute(&$query)
{
$segments = array();
//if(isset($query['view'])) {
// $segments[] = $query['view'];
// unset( $query['view'] );
//}
if (isset($query['task'])) {
$segments[] = implode('/',explode('.',$query['task']));
unset($query['task']);
}
if (isset($query['id'])) {
$segments[] = $query['id'];
unset($query['id']);
}
if (isset($query['name'])) {
$segments[] = $query['name'];
unset($query['name']);
}
unset( $query['view'] );
return $segments;
}
function CountriesParseRoute( $segments )
{
$vars = array();
$app =& JFactory::getApplication();
$menu =& $app->getMenu();
$item =& $menu->getActive();
// Count segments
$count = count( $segments );
//Handle View and Identifier
switch( $item->query['view'] )
{
case 'countries':
if($count == 1) {
$vars['view'] = 'city';
}
break;
case 'city':
$id = explode( ':', $segments[$count-2] );
$name = explode( ':', $segments[$count-1] );
$vars['id'] = $id[0].'-'.$name;
break;
}
return $vars;
}
The way I am calling city pages from view countries is the following:
<a href="<?php echo JRoute::_('index.php?option=com_countries&view=city&id=' . (int)$item->id) .'&name='. $item->city_name; ?>">
Would be amazing if someone can help ! Cheers
If you want to get ride of IDs from urls you will have to add every country menu item or create rooter that will search for item id within database (bad idea with big websites). This will also require setting your homepage to one of your component views. Its easiest way.
When you build router you need two functions. First that will return SEF url CountriesBuildRoute and second that will translate SEF url back to query CountriesParseRoute. It is harder then you actually think to write SEF at this level. I will not write you whole router but only point you to right direction.
In Joomla 1.5 it was easier to make smth you want. If you have time look in rooter from some Joomla 1.5 component like (com_weblinks). CountriesBuildRoute returns array that will build your URL. For example when you return $query array looking like this: array('country','berlin') url will look like you want: domain.com/country/berlin. But reversing that process (something you will do in CountriesParseRoute) gonna be harder. You will have to check if first segment is a country (if it is second should be city).
So in function CountriesBuildRoute check what view is passed and build $segments array directly like you want for your url or selected view to be. Remember that single element from that array will be single segment from URL.
In function CountriesParseRoute check if first array element is a country (db checking, cached countries list, there are many ways to do it) then you will have to do the same with second element from array(if it exists).
I always created BuildRoute first as I wanted. Then spend hours on making parse route as precise and effective as only could be. You can spend hours or even few days if you want to make good router.
I need to create urls for category switching, switching category should reset page to 1st and change cat name but keep rest of url params.
Example of url:
http://example.com/cat/fruits/page/3/q/testquery/s/date/t/kcal/mine/26/maxe/844/minb/9/mint/4/maxt/93/minw/7/minbl/6/maxbl/96
Urls can contain many different params but category name and page should be always first, category without page should work too and show 1st page.
Currently I have defined two routes and I'm using Zend's url helper with named route but it resets params and as end resuls I have /cat/cat_name/page/1 url.
$category_url = $view->url(array('category'=>$list_item['url'],'page'=>1),'category',FALSE)
resources.router.routes.category_main.route = "/cat/:category/*"
resources.router.routes.category_main.defaults.module = "ilewazy"
resources.router.routes.category_main.defaults.controller = "index"
resources.router.routes.category_main.defaults.action = "results"
resources.router.routes.category_main.defaults.category =
resources.router.routes.category_main.defaults.page = 1
resources.router.routes.category.route = "/cat/:category/page/:page/*"
resources.router.routes.category.defaults.module = "ilewazy"
resources.router.routes.category.defaults.controller = "index"
resources.router.routes.category.defaults.action = "results"
resources.router.routes.category.defaults.category =
resources.router.routes.category.defaults.page = 1
Do I need to create custom method for assembling url in this case?
Things I would try:
Add module, controller and action params in $urlOptions (it's the
first array you pass to the view helper)
instead of 'category' route name try null and see what that does for
you.
Try removing this line
"resources.router.routes.category.defaults.category = "
Please specify what version are of zf are you using.
Solution is very simple, one just have to pass all current request params to url helper
(and optionaly overwrite/add some of them, page and category in my case), last variable is set to FALSE to prevent route resetting.
$view->url(
array_merge(
$params,
array('category' => $list_item['url'],
'page' => 1)
),
'category_main',
FALSE
);
Friends a newbie question.........I need help in getting the URL of a specific Menu itemID. The situation is like this:
I am running Joomla and asking for a user to input for a menu ID and choose a layout for that menu ID.
I want to do something else with this URL of the Menu itemID.
How can I get the URL of this Menu itemID provided by the user?
For Example if the user input is liek $this->get ('menulayoutid'>; and he inputs and ID of 54 then how do I get the URL for Menu ID 54.
Please note: I want to get this URL from within my PHP file and not in the browser so that I can use the value of that URL for some other purpose.
Kindly help.
$itemid = JRequest::getVar('Itemid');
$application = JFactory::getApplication();
$menu = $application->getMenu();
$item = $menu->getItem($itemid);
$link = new JURI($item->link);
$link->setVar('ItemId', $itemid);
Source: http://forum.joomla.org/viewtopic.php?p=1836005
However, we get the Itemid from anywhere (user input, from our own developed module using the "menu item" field type in the xml file as described in the Joomla Docs - Standard form field types)
// get the menuItemId from wherever...
// as described above or as in other posts here and do whatever with that!
$menuItemId = 'fromWherever'; // as an example "107";
// build the link to the menuItemId is just easy and simple
$url = JRoute::_('index.php?Itemid=' . $menuItemId);
i think if we need only a link to a specific menu id, this is the best solution, because we have absolutely less requests and a clean code
this works also in Joomla 3.0, 3.1
I just want to add that if you need to target a specific menu you pass the menu name as an argument to getMenu().
$itemid = JRequest::getVar('Itemid');
$application = JFactory::getApplication();
$menu = $application->getMenu( 'menu-name' );
$item = $menu->getItem($itemid);
$link = new JURI($item->link);
$link->setVar('ItemId', $itemid);
I'm not sure if Joomla changed the way this works since 2.5 or even 1.7 but I spent the worse half of 2 hours looking for this.
Hopefully it helps someone.
$menuID = $params->get('menuItem'); // from module field menu ex. '105'
$js = new JSite;
$menu = $js->getMenu();
$link = $menu->getItem($menuID)->route;
//Returns URL Friendly Link -> menu/article
//Then format it ->
$link = 'http://www.yoursite.com/index.php/'.$link;
echo 'Borrowed Menu Link Path";
When you need to get your active menu item ID in Joomla to display some specific content for only that menu item or just to show the ID of the menu item, insert the following code where you wish to display the active menu item ID:
<?php
$currentMenuId = JSite::getMenu()->getActive()->id;
echo $currentMenuId;
?>
I need to make a simple site search with pagination in it; could anyone tell me how to do it without affecting the URL structure? Currently I'm using the default CodeIgniter URL structure and I have removed index.php from it. Any suggestions?
You could just use a url like /search/search_term/page_number.
Set your route like this:
$route['search/:any'] = "search/index";
And your controller like this:
function index()
{
$search_term = $this->uri->rsegment(3);
$page = ( ! $this->uri->rsegment(4)) ? 1 : $this->uri->rsegment(4);
// some VALIDATION and then do your search
}
Just to update this question. It is probably best to use the following function:
$uri = $this->uri->uri_to_assoc()
and the result will then put everything into an associative array like so:
[array]
(
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'
)
Read more about the URI Class at CodeIgniter.com
Don't quite understand what you mean by "affecting the url structure". Do you mean you'd want pagination to occur without the URL changing at all?
The standard pagination class in CI would allow you to setup pagination so that the only change in the URL would be a number on the end
e.g if you had 5 results to a page your urls might be
http://www.example.com/searchresults
and then page 2 would be
http://www.example.com/searchresults/5
and page 3 would be
http://www.example.com/searchresults/10
and so on.
If you wanted to do it without any change to the URL then use ajax I guess.
Code Igniter disables GET queries by default, but you can build an alternative if you want the url to show the search string.
Your url can be in the notation
www.yoursite.com/index.php/class/function/request1:value1/request2:value2
$request = getRequests();
echo $request['request1'];
echo $request['request2'];
function getRequests()
{
//get the default object
$CI =& get_instance();
//declare an array of request and add add basic page info
$requestArray = array();
$requests = $CI->uri->segment_array();
foreach ($requests as $request)
{
$pos = strrpos($request, ':');
if($pos >0)
{
list($key,$value)=explode(':', $request);
if(!empty($value) || $value='') $requestArray[$key]=$value;
}
}
return $requestArray ;
}
source: http://codeigniter.com/wiki/alternative_to_GET/