2
\$\begingroup\$

I'm trying to create URL parse class., so i can check URL Segment / part,

Example:

  1. http://localhost/myproject/class/method/arg/other (localhost)
  2. http://www.myproject.com/class/method/arg/other (live site)
  3. http://www.myproject.com/class/method/arg/other?param=value (with get param)

In urls above:

  • $url->segment(1) : class
  • $url->segment(2) : method

If argument null, it will return the last segment:

  • $url->segment() : other

I need suggestions for improvement this class, here is the code:

<?php
class url
{
 private $url;
 public function segment($arg=null)
 {
 if($arg==null)
 {
 $this->url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']);
 if(isset($_GET))
 {
 $this->url = explode('?',$this->url);
 $this->url = $this->url[0];
 }
 $this->url = explode('/', trim($this->url, '/')); 
 return end($this->url);
 }
 else
 {
 $this->url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']);
 if(isset($_GET))
 {
 $this->url = explode('?',$this->url);
 $this->url = $this->url[0];
 }
 $this->url = explode('/', trim($this->url, '/'));
 array_unshift($this->url, null);
 unset($this->url[0]);
 if(isset($this->url[$arg]))
 {
 return $this->url[$arg];
 }
 else
 {
 return null;
 }
 }
 }
} 
?>
palacsint
30.3k9 gold badges81 silver badges157 bronze badges
asked Jan 23, 2012 at 13:31
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Just a quick note: there is some duplication in the two branches of the first if. You could write the following:

<?php
 public function segment($arg=null)
 {
 $this->url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']);
 if(isset($_GET))
 {
 $this->url = explode('?',$this->url);
 $this->url = $this->url[0];
 }
 $this->url = explode('/', trim($this->url, '/')); 
 if($arg==null)
 {
 return end($this->url);
 }
 else
 {
 array_unshift($this->url, null);
 unset($this->url[0]);
 if(isset($this->url[$arg]))
 {
 return $this->url[$arg];
 }
 else
 {
 return null;
 }
 }
 }
} 
?>

Actually, the else keyword is unnecessary since if the $arg == null condition is true the function returns.

 ...
 if($arg==null)
 {
 return end($this->url);
 }
 array_unshift($this->url, null);
 unset($this->url[0]);
 if(isset($this->url[$arg]))
 {
 return $this->url[$arg];
 }
 // else is unnecessary here too
 return null;
answered Jan 23, 2012 at 14:52
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.