Hi i am writing the following code in the ZipcodeClassHelper.php
public function get_zip_point($table,$zip) {
App::import('Model','Driver_location');
$MyModel = new Driver_location();
$qry = $MyModel->find("all",array('conditions'=>array('zip'=>$zip)));
pr($qry); exit;
}
I got the error message:
Error: Class 'Driver_location' not found
File: E:\xampp\htdocs\2014\cab-zone\cabs\app\View\Helper\ZipcodeClassHelper.php
Line: 25
Loading a Model in CakePHP when not inside a Controller can be done like this:
$ModelName = ClassRegistry::init('ModelName');
Then query the model:
$result = $ModelName->find('all');
That's violating the MVC pattern, you don't fetch data in the view. Your model is not well named either, it doesn't follow the convention, it should be DriverLocation.
Set your data from the controller to the view:
$this->set('whatever', $this->Model->find('...'));
Do the blog tutorial to get an idea of how Cake work with it's conventions and MVC.
Related
I've got a very bad structured proj in Yii2, so if possible please don't pay attention to it.
Here is my proj structure:
In results.php I want to use my FlightsController class.
here is my include section from results.php:
include \yii\helpers\Url::to('#app/views/site/partials/header.php');
include \yii\helpers\Url::to('#app/controllers/HotelController.php');
include \yii\helpers\Url::to('#app/controllers/ActivitiesController.php');
include \yii\helpers\Url::to('#app/controllers/FlightController.php');
FlightController class:
class FlightController
{
require_once(\yii\helpers\Url::to('#app/sabre/rest_activities/LeadPriceCalculator.php'));
public static function start_rest_workflow($origin, $destination, $departureDate){
$workflow = new \Workflow(new \LeadPriceCalendarActivity($origin, $destination, $departureDate));
$result = $workflow->runWorkflow();
}
}
Here I get the error:
yii\base\ErrorException Expected array for frame 0
/controllers/FlightController.php yii\base\ErrorException::__toString
/views/site/results.php yii\web\View::unknown
In the first import require_once(\yii\helpers\Url::to('#app/sabre/rest_activities/LeadPriceCalculator.php')); .
How Can I correctly import a class from sabre directory from controllers directory?
i think that you don't know or not understand MCV software architecture pattern that it is working in yii2.
I m gona try to explain you a resum and a few sugerences :)
What is MVC :
Model: database and his logic.
View: html code and show/render the data.
Controller: big part of logic of code.
Then , whe you need a new page in you website , yo need think , is a other part of the same think or it isn't. If it is the same you must set the file in same path that other , like this example .
You have:
User/form.php
User/index.php
And you want to add a new page "view" where it see the data in a list , than the "view" is part of same think (User) you must set in the same page :
User/view.php
User/form.php
User/index.php
Then , in the controller you must write a big part of you logic that one think , in this case User , and in this Controller will be 3 actionsthan miniumm ( because you have 3 view )
UserController.php
public function actionView($id){
}
public function actionIndex(){
}
public function actionForm(){
}
And the last to explain is a models , it is simple , this are a object to represent a tables in you DB and you must be use like that , you can write a querys in this and call from controller and make somethiks.
In resume , if you will create "result.php" and you like write clean
code you set this file out of path "site" and create other "flight"
by exmaple , and now you can use the code from
FligthController.php en the function inside
public function actionResult(){}
I have a Model - Car - the Car has several associated models, lets consider one of them which is linked with the hasMany relationship - Wheel
In my CarsController, I dynamically generate a datasource using the following code -
$schemaName = $this->Session->read('User.schema');
$config = ConnectionManager::getDataSource('default')->config;
$config['database'] = $schemaName;
ConnectionManager::create($schemaName, $config);
Then I set this datasource in my Car Model using the following line of code
$this->Car->setDataSource($schemaName);
After this I am able to query and operate on Car, however, if I try to operate on Wheel using the following statements - I get an error
$this->Car->Wheel->create();
$this->Car->Wheel->save($wheelData);
The error I get is -
Error: [MissingTableException] Table wheels for model Wheel was not found in datasource default.
For some reason the datasource is not being passed from Parent model to associated child models. If I explicitly set the datasource in Wheel using the following line then everything works fine.
$this->Car->Wheel->setDataSource($schemaName);
Can anyone help shed some light on this behavior and how to fix this? The reason I find this inconvenient is that my parent model has several associated models (which further have associated models) and setting datasource individually on each of them doesnt sound right.
Side Question - is there a way to check if a datasource already exists before trying to create one dynamically? I have a for-loop that wraps this entire code and each loop iteration will end up creating a new datasource
I am using CakePHP 2.5.4
Here is some code which will pass the setDatasource() call to associated models, if you want only the Car model to pass through its datasource put this code in the Car model, if you want all models to pass through, put it in AppModel.php
public function setDatasource($datasource = null) {
foreach (array_keys($this->getAssociated()) as $modelName) {
$this->{$modelName}->setDatasource($datasource);
}
parent::setDatasource($datasource);
}
To answer your comment, I would add public $dynamicDb = false in AppModel.php, meaning false would be the default value for this variable, then in your models override it by adding public $dynamicDb = true, then change the above function to:
public function setDatasource($datasource = null) {
foreach (array_keys($this->getAssociated()) as $modelName) {
if ($this->{$modelName}->dynamicDb === true) {
$this->{$modelName}->setDatasource($datasource);
}
}
parent::setDatasource($datasource);
}
(I haven't tested this amended function as I'm not on my dev PC right now, but its a fairly simple change and it should work)
To check if a datasource already exists before you create one, I can see two possible methods, one is by calling ConnectionManager::getDatasource($schemaName) and catching the exception if the datasource does not exist, or call ConnectionManager::sourceList() and check if your $schemaName is in the returned array, here's an implementation of the first option:
$schemaName = $this->Session->read('User.schema');
try {
ConnectionManager::getDatasource($schemaName)
} catch (MissingDatasourceException $e) {
$config = ConnectionManager::getDataSource('default')->config;
$config['database'] = $schemaName;
ConnectionManager::create($schemaName, $config);
}
and the second option:
$datasources = ConnectionManager::sourceList();
$schemaName = $this->Session->read('User.schema');
if (!in_array($schemaName, $datasources)) {
$config = ConnectionManager::getDataSource('default')->config;
$config['database'] = $schemaName;
ConnectionManager::create($schemaName, $config);
}
Hope this helps
I have a little trouble with naming convention in CakePHP 1.3. I've element called storeItem.ctp, when I'm trying to call it from another view - it works perfect, but when I'm trying to use it as view for action($this->viewPath = 'elements'; and then $this->render(null, 'ajax', '/canvas/storeItem');) I'm getting the error: Error: Confirm you have created the file: ***views/elements/canvas/store_item.ctp.
How can I fix it without renaming element?
An explanation why your code does not work as expected is written in the second paragraph from the bottom in the cookbook. You should try it this way:
$this->layout = 'ajax';
$this->render('/elements/canvas/storeItem');
I'm trying to understand the MVC pattern. Here's what I think MV is:
Model:
<?php
if($a == 2){
$variable = 'two';
}
else{
$variable = 'not two';
}
$this->output->addContent($variable);
$this->output->displayContent();
?>
View:
<?php
class output{
private $content;
public function addContent($var){
$this->content = 'The variable is '.$var;
}
public function displayContent(){
include 'header.php';
echo $content;
include 'footer.php';
}
}
?>
Is this right? If so, what is the controller?
The controller is your logic, the model is your data, and the view is your output.
So, this is the controller:
$model = new UserDB();
$user = $model->getUser("Chacha102");
$view = new UserPage($user->getName(), $user->getEmail());
echo $view->getHTML();
The model is the UserDB class which will give me my data. The view is the UserPage that I give the data from the model to, and it will then output that page.
As you can see, the controller doesn't do much in this example, because you are simply getting user data and displaying it. That is the beauty of MVC. The controller doesn't have to deal with the User SQL or HTML stuff, it just grabs the data and passes it to the view.
Also, the view doesn't know anything about the model, and the model doesn't know anything about the view. Therefore, you can chance the implementation of either, and it won't affect the other.
Relating more to your example, you have the view correct, but you have mixed your controller and model.
You could relieve this by:
Controller:
$model = new NumberToWord();
$word = $model->getWord($a);
$this->output->addContent($word);
$this->output->displayContent();
Model:
class NumberToWord{
public function getWord($number)
{
if($number == 2){
return 'two';
}
else{
return 'not two';
}
}
}
And keep your same output
Controllers receive user requests - usually there is some kind of router that takes a URL and routes the request to the appropriate controller method.
Models are used by a controller to query data to/from a database (or other data source).
Views are called from a controller to render the actual HTML output.
If all you want to do is create a simple template system, you might aswell go with:
$content = 'blaba';
$tpl = file_get_contents('tpl.html');
echo str_replace('{content}',$content,$tpl);
With a template file like:
<html>
<head><title>Whatever</title></head>
<body>{content}</body>
</html>
In your example, it's more like you've split a Controller into a Model and a View.
Model: Business logic / rules and typically some sort of database to object relational mapping
Controller: Responds to url requests by pulling together the appropriate Model(s) and View(s) to build an output.
View: The visual structure the output will take. Typically a "dumb" component.
It can be confusing when you first encounter MVC architecture for a web app, mainly because most web frameworks are not MVC at all, but bear a much closer resemblance to PAC. In other words, the Model and View don't talk, but are two elements pulled together by the context the Controller understands from the given request. Check out Larry Garfield's excellent commentary on the subject for more information:
http://www.garfieldtech.com/blog/mvc-vs-pac
Also, if you are interested in the MVC pattern of development, I suggest you download one of the many frameworks and run through a tutorial or two. Kohana, CodeIgnitor, CakePHP, and Zend should be enough to kick-start a Google-a-thon!
Zend Framework: Surviving The Deep End has some good sections explaining MVC. Check out the MCV Intro and especially this seciton on the model.
There are numerous interpretations of the Model but for many programmers the Model is equated with data access, a misconception most frameworks inadvertently promote by not obviously acknowledging that they do not provide full Models. In our buzzword inundated community, many frameworks leave the definition of the Model unclear and obscured in their documentation.
To answer "where's the controller":
Controllers must define application behaviour only in the sense that they map input from the UI onto calls in Models and handle client interaction, but beyond that role it should be clear all other application logic is contained within the Model. Controllers are lowly creatures with minimal code who just set the stage and let things work in an organised fashion for the environment the application operates in.
I think you'll fine it (and his references of other articles and books) a good read.
Here is a very simple example of MVC using PHP. One thing missing is THE router. It selects one of the controller to do the job. We have only one controller, the customer.
If we compare it with 3 tiers
Model: The database
View: Client
Server:Controller
Router:It selects a controller
When you select something from an application on web browser, the request goes to router, from router it goes to controller. Controller asks from model and make a view. View is rendered to you.
Only model can talk to controller back and forth.
1- Model.php
<?php
class Model
{
private $con=null;
private $r=null;
function connect()
{
$host="localhost";
$db="mis";
$user="root";
$pass="";
$this->con=mysqli_connect($host,$user,$pass) or die(mysqli_error());
if(!$this->con){
echo die(mysqli_error());
}
else mysqli_select_db($this->con,$db);
}
function select_all()
{
$this->connect();
$sql="select * from customers";
$this->r=mysqli_query($this->con,$sql) or die(mysqli_error());
return $this->r;
}
function display_all()
{
$i=0;
echo "aaaaaaaaaa";
$this->r=$this->select_all();
while($q=mysqli_fetch_array($this->r))
{
$i++;
echo $i."-Id:".$q['id']."</br>";
echo $i."-Name:".$q['name']."</br>";
echo $i."-Phone:".$q['phone']."</br></br>";
}
}
}
?>
2. Controller: There may may be many controllers.
<?php
class Customers extends Model
{
function select_all1()
{
//echo "aaaaaaa";
$this->display_all();
}
}
?>
3. View: There may be many views
<?php
include("model.php");
include("customers.php");
?>
<html>
<head><title>Customers</title></head>
<body>
<?php
$c=new Customers();
echo $c->select_all1();
?>
</body>
</html>
How to use the mvc concept,
I need to add a php file to mvc concept.
Please explain
Before you start adding files, you need to understand what MVC is, i assume that you understand what a controller, model and view is, ok i will try to explain step-by-step on how to add a file. Let's say you want to create a page that grabs some product info from database and shows that on a page called products.php.
Step 1: You create a controller named products.php and put all the variables that will be passed to view as well as function to grab products info from db through model.
Step 2: You create a model named products.php and write a function it it that will grab the product info from db.
Step 3: You create a view named products.php and show all variables coming from controller as well as any html for the layout.
Here is the basic skeletion:
products.php controller
class products_controller extends controller
{
// set a variable to be shown on the view
$this->view->myvariable = 'Our Products';
// call model function to get info from db that will be shown on the view.
$this->load->model('products');
$this->view->db_products = $this->products->getProducts();
// now render the view
$this->view->render();
}
products.php model
class products_model extends model
{
function getProducts()
{
$result = mysql_query("select * from products_table");
$rows = mysql_fetch_assoc($result);
return $rows;
}
}
products.php view
<html>
........
<?php echo $myvariable; // this var comes from controller?>
<?php
// now show products coming from db
foreach ($db_products as $product)
{
echo $product['name'];
echo $product['price'];
echo $product['etc'];
}
?>
........
</html>
Note: This is just an example but depending on which MVC framework you are using, file names and class names or syntax might look different, so you will have to adjust that. However, i have put in the code from my own MVC framework named EZPHP, and as the name suggests, it is very easy to use MVC framework. If you need it just reply through a comment.
Thanks and hope that helps :)