I have been using codeigniter for building small and medium level projects for quite some years now. There are few tweaks and tricks I would love to share with codeigniter enthusiasts to make their work bit easier.
HTML Email Templates
If you are building an newsletter system of email delivery method for sending out different emails with html contents, this one is for you to get the job done seamlessly.
Create a folder in your views directory for email templates e.g. emailtemplates
Create email templates views and save them in the folder. Now we can approach the
[php]
public function send_mail() {
$template = ‘discounts’;
$this->load->library( ’email’ );
$this->email->from( ‘[email protected]’, ‘Some Receiver’ );
$this->email->to( ‘[email protected]’ );
$this->email->subject( ‘Message subject’ );
$this->email->message( $this->load->view( ‘emailtemplates/’ . $template , $data, true ) );
$this->email->send();
}
[/php]
$template is the view file in the emailtemplates folder which would be used to send emails and $data would be an array which would pass the parameters to the view.
The Second (Optional) parameter for the $this->uri->segment()
I use $this->uri->segment quite often to get the data from an url . If you haven’t tried it yet, let me explain it first.
If you have an url like http://helloworld.com/example/trick/ , Using
[php]
$this->uri->segment(1);
[/php]
would return you “example” and $this->uri->segment(2); would return you trick and so on.
By passing second parameter to segment method, you can set the default value for the parameter if no value is returned. You can use $this->uri->segment(2, ‘tweak’); and it would return ‘tweak’ even if there is no second segment of uri.
Remove Index.php from URL
Go to application > config > config.php
Change
[php]
$config[‘index_page’] = "index.php"
[/php]
To
[php]
$config[‘index_page’] = ""
[/php]
Open notepad
Paste the following code
[html]
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
[/html]
Save the file as .htaccess in the root directory
You can replace last line of code if the above .htaccess file doesn’t work.
[php]
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
[/php]
Create Custom Helper
First of all, a CI helper is not a class. It is a PHP file with multiple functions.
Open notepad and create a custom function “hello_world”.
[php]
<?php
if ( ! function_exists(‘hello_world’))
{
function hello_world($var = ”)
{
$var = “Hello World! ”. $var;
return $var;
}
}
[/php]
Save this file to application/helpers/ directory. We shall call it “test_helper.php”
Using the Helper
This is how you’ll use it in your controller.
[php]
$this->load->helper(test_helper’);
echo hello_world(‘John’);
[/php]
it would display
Hello World! John
- Tags:
- codeigniter
- php