so I'm trying to make my own MVC website, I figured the best way to learn PHP better and tackle the big MVC issue is to start a full project. The thing is, I'm stuck at the router, I can't figure out how best to write it, I think this may be a good way at least for the moment but I'm not sure if it is a ..viable one. I was basically thinking of calling the right controller according to the switch case and then if there is a second url param(I've assumed it would be the id of a article for now) to call a method calling a single article and if there isn't a second param to call a method that calls all articles, but I would like to know if this is a bad way of doing it.
function call($controller, $id='') {
switch($controller) {
case '':
break;
case 'pages':
$controller = new PagesController();
break;
case 'articles':
require_once('controllers/' . $controller . 'Controller.php');
require_once('models/articles.php');
$controller = new ArticlesController();
if(!$id){
$controller->{ "blog" }();
}else{
$controller->{ "article" }($id);
}
break;
default:
header("HTTP/1.0 404 Not Found");
include('/views/404.php');
exit;
break;
}
}
P.S. For now I'm only working with the articles case, that's why the first case only breaks without doing anything and such. Thanks in advance.
Sure can, see the example below (this is proof of concept and not tested).
switch ($controller) {
case 'pages':
break
case 'articles':
if ($Apples != $Pears)
{
$Tomatoes="Red";
}
case "52":
case "109":
case "110":
//do nothing and exit from switch
break;
default:
if ($a == $b)
{
$c = "cats!";
}
break;
}
Note that you can also use a switch inside a switch, just like nested if statements.
If you have only 2 or 3 option then you can use if else otherwise use nested switch.
You can use if in switch also switch in another switch.
Related
Is there a syntax error in my code? Everything seems to work ok..This is a question asked on a self study test, and I don't want to get caught in a 'stump the chump', trick question..
$i = fgets(STDIN);
switch ($i) {
case 'a':
case 'i':
case 'e':
case 'u':
case 'o':
echo("vowel\n");
default:
echo("non vowel\n");
}
While it does work, it's not quite "right". You forgot to break out of the vowel case.
Personally, however, I wouldn't use a switch for this. I would probably do:
$vowels = ['a','e','i','o','u'];
if( in_array(strtolower($i),$vowels)) {
echo "vowel\n";
}
else {
echo "consonant\n"; // the proper word for "non-vowel" :p
}
This is because you have a two-case statement: either it is, or else it isn't. switch is suboptimal for this kind of thing, and - as shown by the error in your code - more prone to errors ;)
I have an issue with this switch case, I will be glad if someone could give me a hint on what's going wrong.
The lines below keep on adding the case 1, 2 or 3 below the default one (centre_1) instead of replacing it.
I can't find where it goes wrong. Here is the code :
<?php include("mx/centre_1.php");
if(!isset($_GET['page'])) {
$page='centre_mx.php';
} else {
switch($_GET['page']) {
case'centre_1':
include('/mx/centre_1.php');
break;
case'centre_2':
include('/mx/centre_2.php');
break;
case'centre_3':
include('/mx/centre_3.php');
break;
}
}
?>
Any assistance will be helpful.
The reason '/mx/centre_1.php' is always being displayed is because you have it at the top of your code, outside of the if and switch statement. Due to this it'll be included on every page load.
In order to only have '/mx/centre_1.php' appear when no other option is selected you need to make it the default switch case.
$page = '';
if(in_array('page', $_GET)) {
$page = $_GET['page'];
}
switch($page) {
case 'centre_2':
include('/mx/centre_2.php');
break;
case 'centre_3':
include('/mx/centre_3.php');
break;
default:
include('/mx/centre_1.php');
}
The default case in a switch statement will happen when none of the other cases match the variable provided. That is, if $_GET['page'] doesn't equal centre_2 or centre_3 then the default code will be performed.
I'd suggest reading up more on switch statements here, since you don't seem to understand how they work.
I'm building a site on the CodeIgniter framework and I'm using PHP switch to load the specific javascript relevant to the page. My issue comes when I get to the 3rd URI segment, which is generally a variable. for instance I have no issue with say
case 'foo/bar':
but what if my url was something like http://mysite.com/foo/bar/1234, where the 1234 if a variable passed to the controller. It obviously wouldn't make sense to write out a case for every single variable because there's about 30k right now.
currently here's a working snippet of my code...
switch( $this->uri->uri_string() ) {
case '':
break;
case 'browse':
break;
case 'contest/leaderboard':
You could also explode the url on the forward slash and then check each element of an array.
for example
$url_parts = explode('/', $this->uri->uri_string());
switch($url_parts[0]){
case 'foo':
if(count($url_parts) > 1){
if($url_parts[1] == "bar"){
// when the url begins with foo/bar
}
}
break;
case 'browse':
//when url is browse
break;
}
The benefit of this is you could include code common to all urls that begin with foo. Not sure if this is required but could be useful possibly
So then you use "starts with" conditions:
$uri = $this->uri->uri_string();
if (0 === strpos($uri, 'foo/bar')) {
// starts with foo/bar
} elseif (0 == strpos($uri, .... etc
We currently use Switch case url config to help us with the navigation on some of our urls, Im not sure if there is an easier way to do it but i couldnt seem to find 1.
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
}
}
?>
Now this system works perfectly but the only snag we hit is if they type in xxxxxx.php?step=3 boom they just get a blank page and that should be correct as there is no case for it to handle '3' but what i was wondering is .. is there any php code i could add to the bottom that may tell it for any case other than those 2 to redirect it back to xxxxx.php ?
Thanks
Daniel
Use the default case. That is, change your switch to something like this:
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
default:
// Default action
break;
}
}
?>
The default case will be executed for every case which is not explicitly specified.
All switch statements allow a default case that will fire if no other case does. Something like...
switch ($foo)
{
case 1:
break;
...
default:
header("Location: someOtherUrl");
}
would work. You may, however, want to Google around for other, more robust and extensible, page dispatch solutions.
How about a different approach with something along the lines of:
<?php
$currentStep = $_GET['step'];
$includePage = './step'.$currentStep.'.php'; # Assuming the pages are structured the same, i.e. stepN where N is a number
if(!file_exists($includePage) || !isset($currentStep)){ # If file doesn't exist, then set the default page
$includePage = 'default.php'; # Should reflect the desired default page for steps not matching 1 or 2
}
include($includePage);
?>
I have a php file in which i am using a really very long switch case. I want to split the cases in different files (keep logically connected cases in 1 file).
EDIT: Sorry everyone it was my code that was causing problem. The switch case was working as expected.
file -> a.php
echo "<br>RES = ".test(1);
function test($value) {
switch($value) {
case (1 || 2):
include("b.php");
**return $temp;**
break;
default: echo "error";
return 3;
break;
}
}
file -> b.php
switch($value) {
case 1: echo "value is 1";
**$temp = 1;**
return 1;
break;
case 2: echo "value is 2";
**$temp = 2;**
return 2;
break;
}
How do i get proper result? if the switch case of b.php is in a.php file then everything works fine.Any idea/suggestion on how to do this?
If i add $temp (bold lines) then it works...
Thanks for help in advance.
Regards
Updated response to updated question:
modify "a.php" and prefix a return infront of the "b.php" include:
return include("b.php");
http://www.php.net/manual/en/function.include.php
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it. Also, it's
possible to return values from
included files. You can take the value
of the include call as you would a
normal function. This is not, however,
possible when including remote files
unless the output of the remote file
has valid PHP start and end tags (as
with any local file). You can declare
the needed variables within those tags
and they will be introduced at
whichever point the file was included.
simple include()'s within your case/break sections?
switch($var)
{
case 1:
include('case_1.php');
break;
case 2:
include('case_2.php');
break;
default:
include('case_default.php');
break;
}
This is actually something that Scuzzy proposed (I have even left the same naming convention), but improved:
// list of files
$my_files = array(
'a' => 'case_1.php',
'b' => 'case_2.php',
'c' => 'case_3.php',
'd' => 'case_4.php',
);
// determine which one to load
if (array_key_exists($var, $my_files)) {
include($my_files[$var]);
} else {
include('case_default.php');
}
or even shorter ;) :
$f = array('a','b','c','d');
include((in_array($var,$f)?$var:'case_default').'.php');
switch($var)
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: //...
include('case_' . $var . '.php');
break;
default:
include('case_default.php');
break;
}