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(){}
Related
I'm posting this after my hair has been ripped out, ran out of rum, and tried everything I can find on google. I've been developing a site using codeigniter which makes use of templates. I've built the backend first and all is working properly there. So now i've started on getting the front end working which is where I'm hitting the issue.
I've created a controller called pages.php which is going to parse the uri string of the current page, use my library to get the page data from the database, then display it. My pages are all created through an editor on the back end and stored in the database.
So here's the pages controller
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library("pages");
}
public function display_page()
{
$page_slug = $this->uri->segment(1);
$data["joes"] = "Here's joes first variable";
$this->pages->get_page($page_slug);
}
}
and here's the error message i get when i hit my url like this demo.mydomain.com/joes-test
and here is how my routes are set up. $route['(:any)'] = 'pages/display_page';
My Pages.php library works perfect on the back end but it's a large file. I've only posted the get_page function below. If you need to see everything let me know. But i dont believe the issue has anything to do with the library itself.
public function get_page($slug){
$objPages = new pages();
$objPages->get_object('slug="'.$slug.'"');
return $objPages;
}
[EDIT] If i place the following inside my homepage controller it works. But the calling function needs to be inside the library.
$this->load->library('pages');
$the_page = $this->pages->get_page("joes-test");
I want to call $this->get_object("joes-test") but this doesn't work. get_object() is an inherited function inside the library.
Now oddly enough. The code i put above will NOT work if i do the exact same thing inside the pages controller
any help leading to a solution would be awesome. I'm under a time crunch and pay to get some assistance. Thanks in advance.
No you can't use the same name with controller and library. please choose another name. for example Mypages for you controller name.
change your routes
$route['(:any)'] = 'mypages/display_page';
then call your controller.
http://demo.mydomain.com/joes-test
I think there nothing wrong with library uri, because as codeigniter official website say: This class is initialized automatically by the system so there is no need to do it manually.
I don't know about lib pages, but how about use
$this->load->view(<file-html>);
and if you want to passing data in variable, you can add variable like this
$this->load->view(<file-html>, $data);
Hope this help, Cheers
I have function in ProductsController productsCount(). It give me amount of records in table.
public function productsCount() {
$productsAmount = $this->Products->find('all')->count();
$this->set(compact('productsAmount'));
$this->set('_serialize', ['productsAmount']);
}
I want to call this function in view of PageController. I want to simply show number of products in ctp file.
How can i do this?
You can use a view cell. These act as mini controllers that can be called into any view, regardless of controller.
Create src/View/Cell/productsCountCell.php and a template in src/Template/Cell/ProductsCount/display.ctp
In your src/View/Cell/productsCountCell.php
namespace App\View\Cell;
use Cake\View\Cell;
class productsCountCell extends Cell
{
public function display()
{
$this->loadModel('Products');
$productsAmount = $this->Products->find('all')->count();
$this->set(compact('productsAmount'));
$this->set('_serialize', ['productsAmount']);
}
}
In src/Template/Cell/ProductsCount/display.ctp lay it out how you want:
<div class="notification-icon">
There are <?= $productsAmount ?> products.
</div>
Now you can call the cell into any view like so:
$cell = $this->cell('productsCount');
I think it would make more sense to just find the product count in the PageController. So add something like $productsAmount = $this->Page->Products->find('all')->count(); in the view action of PageController, and set $productsAmount. If Page and Products aren't related, then you can keep the find call as is as long as you include a use for Products.
Also check this out for model naming conventions: http://book.cakephp.org/3.0/en/intro/conventions.html#model-and-database-conventions
Model names should be singular, so change Products to Product.
you can not call controller method from view page. you can create helper, which you can call from view page.
here you will get a proper documentation to creating helpers-
http://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers
It just depend on the kind of call you're making because there are 3 cases for your issue..
1- If you're calling by a link to click you simply do:
<?= $this->Html->link(_('Product number'),['controller' =>'ProductsController', 'action' => 'productsCount']) ?>
The 2 other cases are whether you want to render the result straight in that same view, then there are some workaround to do.
1- first you will need to check what are the associations between the Page table and the product table and use BelongTo or hasMany option to bind them togheter for proper use.
2- If no association between the tables then you will nedd TableRegistry::get('Produts'); to pass data from a model to another, just like this way in the Pages controller:
public function initialize()
{
parent::initialize();
$this->Products = TableRegistry::get('Produts');
}
But i quite believe that the first option is more likely what you described.
Also you can define static method as below
public static function productsCount() {
return = $this->Products->find('all')->count();
}
And use self::productsCount() in other action.
This is useful only if you need to get count multiple time in controller. otherwise you can use it directly in action as below:
$this->Products->find('all')->count();
I'm using codeigniter multilanguage and it works fine. The problem is when I try to do multilanguage in the URL... how can I do it?
I mean the controller has to be a file, with a name, and its functions too... so I can't figure how can I do it.
The only alternative I thought is create the same controllers for each language I need... but this is a lot of repeated code just for change the name of the controller and functions... and the maintenance will be a big trouble.
Any help?
Pass the language indicator as a "GET" value to your controller functions:
eg.
base_url/controller/inventory/en
Then use it like this in your controller:
/**
* #desc This will get called when no method specified
* Will show home page (list of items)
*/
function inventory($lang="en",$from=0){
// load proper language file
$this->lang->load('language_filename', $lang);
// generate db where clause
$where = array(
"published"=>"1",
"language"=>$lang
);
// paging
$this->_setPagingLinks($this->newsModel->getTotalRecordsNumber($where),10,4,"inventory/".$lang,$lang);
// loading items from db
$this->data["news"] = $this->newsModel->getRecords($where,$from,10,"time");
// load the view according to language
$this->data["content"] = $this->load->view("$lang/news",$this->data,TRUE);
$this->load->view("$lang/container",$this->data);
}
I'm writing a control panel for my image site. I have a controller called category which looks like this:
class category extends ci_controller
{
function index(){}// the default and when it called it returns all categories
function edit(){}
function delete(){}
function get_posts($id)//to get all the posts associated with submitted category name
{
}
}
What I need is when I call http://mysite/category/category_name I get all the posts without having to call the get_posts() method having to call it from the url.
I want to do it without using the .haccess file or route.
Is there a way to create a method on the fly in CodeIgniter?
function index(){
$category = $this->uri->segment(2);
if($category)
{
get_posts($category); // you need to get id in there or before.
}
// handle view stuff here
}
The way I read your request is that you want index to handle everything based on whether or not there is a category in a uri segment. You COULD do it that way but really, why would you?
It is illogical to insist on NOT using a normal feature of a framework without explaining exactly why you don't want to. If you have access to this controller, you have access to routes. So why don't you want to use them?
EDIT
$route['category/:any'] = "category/get_posts";
That WOULD send edit and delete to get_posts, but you could also just define those above the category route
$route['category/edit/:num'] = "category/edit";
$route['category/delete/:num'] = "category/delete";
$route['category/:any'] = "category/get_posts";
That would resolve for the edit and delete before the category fetch. Since you only have 2 methods that conflict then this shouldn't really be that much of a concern.
To create method on the fly yii is the best among PHP framework.Quite simple and powerful with Gii & CRUD
http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
But I am a big CI fan not Yii. yii is also cool though.
but Codeigniter has an alternative , web solution.
http://formigniter.org/ here.
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 :)