[eluser]1cookie[/eluser]
hi
Ive been reading a book about design patterns (strategy) with PHP. I've got it working in native PHP like so:
Code:
<?php
require 'class.lesson.php';
require 'class.coststratergy.php';
require 'class.timedcoststratergy.php';
require 'class.fixedcoststratergy.php';
require 'class.seminar.php';
require 'class.lecture.php';
$lessons[] = new Seminar( 4, new TimedCostStratergy() );
$lessons[] = new Lecture( 4, new FixedCostStratergy() );
foreach ( $lessons as $lesson ){
print "lesson charge: {$lesson->cost()}";
print " - charge type: {$lesson->chargeType()}.<br />\n";
}
echo '<pre>';
var_dump($lessons);
echo '</pre>';
This prints:
Quote: lesson charge: 20 - charge type: Houly Rate.
lesson charge: 30 - charge type: Fixed Rate.
array(2) {
[0]=>
object(Seminar)#1 (2) {
["duration":"Lesson":private]=>
int(4)
["costStratergy":"Lesson":private]=>
object(TimedCostStratergy)#2 (0) {
}
}
[1]=>
object(Lecture)#3 (2) {
["duration":"Lesson":private]=>
int(4)
["costStratergy":"Lesson":private]=>
object(FixedCostStratergy)#4 (0) {
}
}
}
to the browser - correct output!
The trouble begins when I try to acheive the same thing in CI with:
Code:
//controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include ('/var/www/Composition/application/libraries/CostStrategy.php');
include ('/var/www/Composition/application/libraries/Lesson.php');
include ('/var/www/Composition/application/libraries/TimedCostStrategy.php');
include ('/var/www/Composition/application/libraries/FixedCostStrategy.php');
include ('/var/www/Composition/application/libraries/Lecture.php');
include ('/var/www/Composition/application/libraries/Seminar.php');
class Front extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['lessons'] = new Seminar( 4, new TimedCostStrategy() );
$data['lessons'] = new Lecture( 4, new FixedCostStrategy() );
$this->load->view('index', $data);
}
}
Code:
//view:
<!DOCTYPE html>
<html>
<head>
<title>Composition with design patterns</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
foreach( $lessons as $lesson ){
echo "lesson charge: {$lesson->cost()}.";
echo "charge type: {$lesson->chargeType()}\n";
}
/*
* Expecting:
* lesson charge: 20. charge type: Hourly rate
* lesson charge: 30. charge type: Fixed rate
*/
echo '<pre>';
var_dump($lesson->cost());
var_dump($lessons);
echo '</pre>';
?>
</body>
</html>
The above prints:
Quote:A PHP Error was encountered
Severity: Notice
Message: Undefined variable: lesson
Filename: views/index.php
Line Number: 22
Fatal error: Call to a member function cost() on a non-object in /var/www/Composition/application/views/index.php on line 22
to the browser. A uml diagram can be seen
here
So in my codeigniter version
$lesson is not an object?? And you need an instance to call a method right. I'm chasing my tail a bit right now?