Hey,
I am trying to understand the MVC, so i decided to go right back to PHP basics and create a simply miles to km converter.
I have a Models folder, a Views folder and then an index.php file in the source files.
In the Models folder i have a file called “class.converter.php” shown below:-
class Converter {
var $number = 0, $unit = '';
public function __construct($number, $unit) {
$this->number = $number;
$this->unit = $unit;
}
public function convert() {
if (is_numeric($this->number)) {
if ($this->unit == 'miles to km'){
$result = $this->number * 1.609;
} elseif ($this->unit == 'km to miles'){
$result = $this->number * 0.621;
} else {
$result = 'error';
}
} else {
$result = false;
}
return $result;
}
}
Then in Views i have “index.phtml” shown below:-
<html>
<head>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>';?>
<title>Converter</title>
</head>
<body>
<div style="background: #c0c0c0; padding: 10px">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td><label>Convert: </label></td>
<td><input type="text" name="name" value="<? echo $_POST['number'] ?>"></td>
</tr>
<tr>
<td><label>From: </label></td>
<td>
<select name="unit">
<option>km to miles</option>
<option>miles to km</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
<?php if(isset($view->result)) : ?>
<p><?php echo $view->result; ?></p>
<?php endif; ?>
</div>
</body>
</html>
Finally index.php file is as follows, this is located in the source files outside the Model and Views folders:-
<?php
require_once ('Models/class.converter.php');
if(isset ($_POST['submit'])){
$converter = new Converter($_POST['number'], $_POST['unit']);
if(!$result){
$view->result = 'Not a valid number.';
} else {
$value = $converter->convert();
$view->result = 'Converting ' . $_POST['number'] . ' from '
. $_POST['unit'] . ' is ' . $value . '.';
}
}
require_once ('Views/index.phtml');
Now i am running this locally, so i cant show you what i am getting. But I cant seem to echo the result. Whichever input i out in i get “Not a valid number.”…
Can anyone help me with this very simple exercise?