check existence of variable in view via code igniter - codeigniter

In Codeigniter I want to know the best practice for using the same views with various functions in a controller.
For eg in the index function I have
$locals['somevar'] = "some thing";
$this->load->view('welcome_message', $locals);
in my view I have something a bit like this:
<?php if($somevar):?>
<?=$somevar?>
<?php endif;?>
Attempting to do a Ruby on Rails thing where I can check the existence of Flash/notice before showing it.
However in the test function
(i.e not passing a variable to the view this time)
$this->load->view('welcome_message')
the view seems to need a $somevar value and errors.
My question is this: Do I have to declare (repeat) the variables and set them to something on every function in a controller tnat wants to use that particular view? I am probably missing something obvious and there is probably a better way of approaching this. Thanks for you help in advance.

<?php if (isset($somevar)): ?>
<?php echo $somevar; ?>
<?php endif; ?>

Related

Laravel: should i use #include inside loops?

Below i provided two example of displaying product card in a loop. The first one seems to me more convenient but i'm worrying about performance because of this #include inside the loop. As this task is pretty common i would like to choose the best way.
Case 1. Using #include:
search.blade.php
<div id='search-results'>
#foreach($items as $item)
#include('items._item')
#endforeach
</div>
_item.blade.php
<div>
<div class='item-title'>{{$item->title}}</div>
<div class='item-description'>{{$item->description}}</div>
</div>
Case 2. Without #include:
search.blade.php
<div id='search-results'>
#include('items._items_list')
</div>
_items_list.blade.php
#foreach($items as $item)
<div class='item-title'>{{$item->title}}</div>
<div class='item-description'>{{$item->description}}</div>
#endforeach
This can potentially create a huge performance issue. When you loop your #include as in the first case, the generated raw php file does indeed call the included view as a function. This slows down the page rendering somewhat.
The second case is more performant since it basically is 1 include (with a loop containing a html snippet).
I'm encountering this issue right now. I have a datatable which loops 250 records, but each record contains like 5 helpers. In my case these helpers are quite vital and contain some necessary (simple) logic, but even with simple logic, 1250 subviews will result in a massive performance drop, reducing load time of the page to 5-6s compared to 300-400ms when copying over this helper code.
I was taking an effort to write a Laravel extension that would parse all #include and replace it with the actual code, but its not an easy task...
Example 1: Looking at how blade parses your #foreach loop
Consider this very simple foreach loop. It simply outputs the name of an object in an <h1> tag for each element:
#foreach($paymentMethods as $paymentMethod)
<h1>{{ $paymentMethod->name }}</h1>
#endforeach
You can see that the generated data inside storage/framework/views/*.php comes out a bit more complex:
<?php $__currentLoopData = $paymentMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $paymentMethod): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<h3>
<?php echo e($paymentMethod->name);
</h3>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
<?php /**PATH C:\xampp\sites\someproject\resources\views/payment_providers.blade.php ENDPATH**/ ?>
Various helpers from the $__env object are being called. These will for instance add extra functionality to your #foreach loop like the $loop->first/$loop->last variables (see https://laravel.com/docs/5.8/blade).
Example 2: an #include statement
#include('myhelper')
<?php echo $__env->make('myhelper', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
The $__env->make() function resolves to vendor/laravel/framework/src/Illuminate/View/Factory.php, which evaluates your blade helper. This process includes finding the view file itself, parsing it through the blade engine again, dispatching events...
Blade shortcuts will undoubtedly have a performance impact. It only depends on how many you are using and if it's worth the extra few milliseconds for you.
Imho it's a very worthwhile optimization for production environments, if you happen to need to loop big collections and are using many #include statements. I would then suggest to resort to a standard <?php foreach($arr as $item): ?>/<?php endforeach ?> syntax, in combination with some simple php functions that return html if you need re-useable html pieces.
I tested this behavior by using 75 rows that passed to some blade then iterate over this 75 rows twice.
the first using only blade code inside this blade file and the other was call #include another blade file that has the same code and mark the time using microtime(true) php function at start and end of each irritation
The time was increased 3 times in case of using #include.
The first way seems like the most correct way to do this.

How can I read session variables at dokuwikis main.php created outside the dokuwiki pages?

I do create a session variables at a php file containing an index 'fullName'. If I try to access the variable from the dokuwikis main.php an 'Index not found error' appears and no values are saved in that session.
Leaving the dokuwiki and going back to the original php file I can access the varaibale again.
Can someone explain why that happens and how to work around?
Running a phpinfo() I do get back the same path values for session_save_path.
Thanks for your help!
EDIT:
Heres some code:
host.tld/anypage.php:
<?PHP
session_start();
$_SESSION['fullName'] = "any string";
?>
host.tld/dokuwiki eg. /usr/share/dokuwiki/lib/tpl/dokuwiki/main.php:
<html>
<?PHP
session_start();
?>
....
<body>
<?PHP
echo $_SESSION['fullName']; // Index error, no session variables at all
//
?>
//Dokuwiki content
</body>
</html>
DokuWiki's session name is 'dokuwiki'. You either need to change your session name in your external application or in DokuWiki. For the latter have a look at inc/init.php

How to make codeIgniter website in different languages

Thanks to sof for its support.
I have developed my site in codeIgniter. Now my client came up with a requirement that to put website in different languages.
I have checked with
http://backlink-generator.arxiki.com/free-translate-translator-translation.html
It provided a button for translation.But Iam confused whether it is the perfect procedure or not.Please help me Iam new to this concept.
I have even checked this
How to setup CodeIgniter for a truly multi language website?.
Mywebsite is fully developed .I just to make it work for different languages.
There will not be a one button solution for that.
You will need to use a Language library like this: http://jeromejaglale.com/doc/php/codeigniter_i18n
and then get all your texts in the language files , this means that under the language folder you will have a folder for each language you support and in there you will have PHP files with variables that will hold the texts for all the pages. this files will be duplicated to each language folder and the content will be then translated.
On your controllers you will load the right language file and then in the view you will just call the string variable name and according to the language the user is currently in it will pull the string from the language file.
The url of your application will be like this http:www.domain.com/en/controller
hope this helps
Change existing website to multi language website : codeigniter
For this you can use language class. See the steps,
Step 1:
create a new file content_lang.php in application/language/english/ for english language. create another content_lang.php file directory dutch for dutch language in application/language/dutch (Create a directory if not exist).
In this file we can write the different languages. Like,
application/language/english/content_lang.php
<?php
$lang['key']='en';
$lang['home']="Home";
$lang['about']="About Us";
$lang['login']="Sign In";
?>
application/language/dutch/content_lang.php
<?php
$lang['key']='dh';
$lang['home']="huis";
$lang['about']="over ons";
$lang['login']="Aanmelden";
?>
Step 2:
Put the language values at the view at the place text. application/views,
Like,
application/views/index.php
<ul>
<li class="current_page_item"><?php echo $language['home'];?></li>
<li><?php echo $language['about']?></li>
<li><?php echo $language['login']?></li>
</ul>
Step 3:
In your controller you can load the language files like,
application/controllers/users.php
function Index()
{ $languages = $this->session->userdata('languages');
$lg=$languages['language'];
if($lg=='en'){
$this->lang->load('content','english');
}
elseif($lg=='dh'){
$this->lang->load('content','dutch');
}
else{
$this->lang->load('content','english');
}
$data['language']=array(
'home'=>$this->lang->line('home'),
'about'=>$this->lang->line('about'),
'login'=>$this->lang->line('login')
);
$lg=$this->lang->line('key');
$data['val']=array(
'lang'=>$lg
);
$this->load->view('index',$data);
}
Here we can pass two language data and their key value for switching language to view. $data['language'] and $data['val'].
To change the language, (application/controllers/users.php)
function changeLanguage(){
if(isset($_POST)){
$this->session->unset_userdata('languages');
$lg=$this->input->post('sel_lang');
$lang=array(
'language'=>$lg
);
$this->session->set_userdata(array('languages'=>$lang));
redirect('users/Index');
}
}
Step 4:
Code to switching languages on views. (application/views/index.php)
<form id="frm_lg" action="changeLanguage" method="post">
<?php echo $language['lang_select'];?>
<select id="sel_lang" name="sel_lang">
<option value='en' <?php if($lang=='en'){?> selected <?php } ?>>English</option>
<option value='dh' <?php if($lang=='dh'){?> selected <?php } ?>>Nederlands</option>
</select>
</form>
Like this way we can load nay number of languages.
Download the example code, Github

Can I query database directly from view in codeigniter?

When I loop data from database I need value from that to query again. I query database directly from view. I want to know that is my code wrong? If wrong what is the better way?
foreach($data->result() as $row1) {
echo '<li>';
echo $row1->Name;
echo '<ul>';
$this->db->select('Photo');
$this->db->from('tblPhoto');
$this->db->where('User_id', $row1->User_id);
$photo = $this->db->get();
foreach($photo->result() as $row2) {
echo '<li>';
echo $row2->Photo;
echo '</li>';
}
echo '</ul>';
echo '</li>';
}
The way you're doing it will work, but you may want to consider separating your code to make your code more reusable. For example:
<~~~~ controller ~~~~~>
// your_controller.php:
$this->load->model('your_model');
$data = $this->your_model->get_data();
foreach($data as $key => $obj)
{
$data[$key]->photos = $this->your_model->get_photos($obj->User_id);
}
$this->load->view('test', array('my_data' => $data));
<~~~~ model ~~~~~>
// your_model.php
function get_data()
{
return $this->db->get('yourTable')->result();
}
function get_photos($user_id)
{
return $this->db->get_where('tblPhoto', array('User_id' => $user_id))->result();
}
<~~~~ view ~~~~~>
your_view.php
<?php foreach($my_data as $row1): ?>
<li>
<?php echo $row1->Name;?>
<ul>
<?php foreach($row1->photos as $row2): ?>
<li><?php echo $row2->Photo; ?></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
Ideally view is not right place to do this.
Firstly all data must be processed between controller/model and should be passed to view.
If case you have a scenario where you want to get data from view after rendering, you should make an ajax call from view to controller and then ask controller to get data from model(data layer).
And respond with data from controller to view and reflect html changes in view depending upon the data received if any changes required.
This is how an MVC architecture should be.
#lyhong, your code is programmatically right.
But, using Codeiginter MVC standards is advisable.
The queries should reside in Models.
So that they can become reusable.
Queries written in Views will serve only that view.
Also, if your write queries in View files, following issues should occur:
In case you do not get
$row1->User_id
the errors should be displayed directly on the page.
Also, it will load your view file slowly.
Benefit of sticking to MVC standards is huge extendibility.
The accepted answer is certainly as good as it gets. I would say that it's worth describing /WHY/ we don't make db queries inside the view. Imagine the view as just that - a view, or a way of viewing the data, or a version of viewing the data (it could be presented in many ways, and the version of how it's presented might change over time, such as they way FaceBook looks now vs. 10 years ago).
And an HTML view is only one way it could be presented; the data could be "viewed" as a PDF, a spreadsheet, a JSON package to be consumed by a microservice, etc. etc.. So if you're NOT calling a database for more information, it's a good indication that you've configured your data well, and it's likely it could be used in multiple ways, robustly.
OK, so guess what? Everything I just said is garbage. I hope you didn't believe it. In actuality, modern presentations and customization present their own complexities such that how the view is to be presented depends on what the data is, the resulting query of which is going to make the needed $data payload needed to be much more complex and possibly take unnecessary time for something that doesn't want to be shown. Run that through to it's logical conclusion, and you'll see the limitations of passing every possible scenario through the view data.
What #abhinsit said above about calling the ancillary stuff via AJAX is a valid point, but know that that adds complexity. But if done well it could save time and make things simpler overall. A good example is including the user information (Hello John Smith) by post-rendering with AJAX. Don't feel guilty if you see a valid need to call the database in the view, but try and structure your view (and your entire framework) so that the important things are already set in state.

Codeigniter: Retrieving data from multiple tables and displaying results

I am developing my first big application using codeigniter and need a little help as I am fairly new to it all. I know how to get records out of the DB and display them, but I now have to get results from two tables and display them. I pass $data to the view, it works fine for $data['prop'] but I can't get the rest.
$data['prop'] = $this->ManageProperty_model->get_property_details($p_id);
$data['img'] = $this->ManageProperty_model->get_property_images($p_id);
$this->load->model('ManageBranch_model');
$data['branch'] = $this->ManageBranch_model->get_branch_details($p_id);
I usually echo out results like so:
<?php foreach ($prop as $p) : ?>
<?php echo $p->ID; ?>
<?php endforeach; ?>
Even if there is only 1 row being returned as I am not sure of another way.do I need a foreach for img and branch?
How about using a join?
I dont know whats in your model but if you try something like
$this->db->from('property');
$this->db->join('branch', 'branch.id = property.id');
You can put a where statement in there too if you need something particular.
This means you have a more complex model but less loops and arrays and messy stuff in the view which is what you want.
Yes, currently you're just getting one or the other. You're probably better to put it into a multilevel array like $data['property']['prop'].

Resources