CodeIgniter - Displaying and entering dynamic meta data - codeigniter

I have started using CodeIgniter ... Im finding it is quite good, although I have a bit of an issue.
Whats the best way to handle meta data? ... In the views folder, I have created another folder called 'includes' then in there I have added header, footer, nav views.
So I'm taking it that for each controller meta data needs to be entered and then passed to the header view.
If I could get some examples of how you all go about this, that would be fantastic.
Cheers,

I know this is an out of date question, but in case anyone is looking for a simple solution for this in Codeigniter 2.2
I found the simplest thing was to create a helper for this.
Create a file located in config/seo_config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['seo_title'] = 'My title';
$config['seo_desc'] = 'My description';
$config['seo_robot'] = true;
/* End of file seo_config.php */
/* Location: ./application/config/seo_config.php */
Create a file located in application/helers/seo_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* SEO Helper function
*
* Generates Meta tags for SEO
*
* #author Henrik Oldenborg
* #version 1.0
*/
/**
* meta_tags()
*
* Generates tags for title, description and robots
* Using title and description from config file as default
*
* #access public
* #param string Title
* #param string Description (155 characters)
* #param bool Robots follow or no folow
*/
if(! function_exists('meta_tags')){
function meta_tags($meta)
{
$CI =& get_instance();
$CI->config->load('seo_config');
if(!isset($meta['title']))
$meta['title'] = $CI->config->item('seo_title');
if(!isset($meta['desc']))
$meta['desc'] = $CI->config->item('seo_desc');
if(!isset($meta['robot']))
$meta['robot'] = $CI->config->item('seo_robot');
$html = '';
//uses default set in seo_config.php
$html .= '<title>'.$meta['title'].'</title>';
$html .= '<meta name="title" content="'.$meta['title'].'"/>';
$html .= '<meta name="description" content="'.$meta['desc'].'"/>';
if($meta['robot'] == true){
$html .= '<meta name="robots" content="index,follow"/>';
} else {
$html .= '<meta name="robots" content="noindex,nofollow"/>';
}
echo $html;
}
}
/* End of file seo_helper.php */
/* Location: ./application/helpers/seo_helper.php */
Load up the helper - (Either in the controller or in config/autoload.php)
$this->load->helper('seo_helper');
Add the following code in your view between the two header tags
<?=(isset($meta) ? meta_tags($meta) : meta_tags());?>
Now, all you need to do is declare the $meta variable in your controller like so
$data['meta']['title'] = 'My special title';
$data['meta']['desc'] = 'My special description';
$this->load->view('mytemplate',$data)
Usefull tip
You might want to declare your meta data in the controllers constructor. This way you can easily override it when needed in a underlying function, like so.
class Forum extends CI_Controller {
private $data = array();
function __construct()
{
$this->data['meta']['title'] = 'My forum title';
$this->data['meta']['robot'] = false;
parent::__construct();
}
public function index()
{
$this->data['content'] = 'forum';
$this->load->view('userarea/template',$this->data);
}
public function topic($topic_id)
{
$this->data['meta']['title'] = 'My specific title';
$this->data['content'] = 'topic';
$this->load->view('userarea/template',$this->data);
}
}

Create a new file in your libraries folder:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class View_lib {
public function __construct()
{
$this->CI =& get_instance();
}
public function load_view($template, $data = NULL)
{
$this->CI->load->view('header', $data);
$this->CI->load->view($template);
$this->CI->load->view('footer');
}
}
/* End of file view_lib.php */
/* Location: ./system/application/libraries/view_lib.php */
Then load this library in your controller:
$this->load->library('view_lib');
Then call your view file in a function like this:
$this->view_lib->load_view('name_of_view_file', $data);
or (if you call a static file without any data to pass):
$this->view_lib->load_view('name_of_view_file');
There are many ways of doing this, but this one works nicely for the applications I am working on. In one of my projects I have multiple functions in the view_lib library to load with or without sidebar, different headers and footers depending if a user is logged in.
Hope this helps, cheers.

I find its just easiet to pass it right in the head of the page with arrays
$meta = array(
array('name' => 'description', 'content' => 'Political website, Liberal, progressive, blog, posts,'),
array('name' => 'keywords', 'content' => 'politics, McCain, Beck, Hannity, Rush Limbaugh, Environment, Obama, ZB Block, Sarah Palin, Republicans, GOP, Democrats, Liberals, Conservatives, Reagan, Politicususa, FreakOut Nation, Raw Story, Congress, Senate, Representatives, Constitution, White, Black, racial, racsim, blog, blogging, Lemon, Lemonrose, Fox, Fox News,
political, partys, president'),
array('name' => 'Content-type', 'content' => 'text/html; charset=utf-8', 'type' => 'equiv'),
);
echo meta($meta);

Related

Create custom plugin joomla with custom ordering on install

Is the a trick to set my custom plugin to load the final plugin in joomla?
I want to set order on install and not after.
Is s there a custom params to set in xml like order="xxx" ?
I just found the answer by adding in the xml file
<scriptfile>script.php</scriptfile>
And in the script file
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* Script file of yourplugin component.
*/
class plgSystemyourplginInstallerScript
{
/**
* method to run after an install/update/uninstall method.
*/
public function postflight($type, $parent)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$fields = array(
$db->quoteName('ordering').' = '.(int) 999,
);
$conditions = array(
$db->quoteName('element').' = '.$db->quote('wraprotect'),
$db->quoteName('type').' = '.$db->quote('plugin'),
);
$query->update($db->quoteName('#__extensions'))->set($fields)->where($conditions);
$db->setQuery($query);
$db->execute();
// $parent is the class calling this method
// $type is the type of change (install, update or discover_install)
}
}
Don't forget to edit your plugin name
And in joomla 1.5 edit #__extensions to #__plugins
And delete the line $db->quoteName('type').' = '.$db->quote('plugin')

codeigniter template engine like in Wordpress Or Joomla

Is there a Codeigniter Library or extension which would make possible dynamic templating like in Wordpress or Joomla. What I mean I would like to point my controller to a view which is specified by admin from back.
than I was starting to create by myself but till this point without any success
controller
--main_conroler
here some trying what did not succeed
class MainController extends CI_Controller {
/* Initiate Site
*/
private $method;
private $data;
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('language');
$this->method = $this->router->fetch_method();
if ($this->method == "index") {
$this->data['view'] = 'templates/appStrapp';
} elseif ($this->method != 'site' && method_exists(__CLASS__, $this->method)) {
$this->data['view'] = $this->method;
}
if (empty($this->data['view'])) {
show_404();
}
}
View
view
--templates
---default
----index.php
than here I would like to route my template parts
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if (file_exists(dirname(__FILE__) . '/tmpl/' . $view . '.php')) {
include ( dirname(__FILE__) . '/tmpl/header.php');
include ( dirname(__FILE__) . '/tmpl/navigation.php');
$this->load->view('site/tmpl/' . $view);
include ( dirname(__FILE__) . '/tmpl/footer.php');
} else {
var_dump('test');
show_404();
}
?>
I've used the following for templates in CI and it's a nice setup.
https://github.com/philsturgeon/codeigniter-template

Anchor Text - Can you hide it? (URL Helper)

Is there anyway to hide the anchor text of the generated by CI? I know I could hide this via CSS (i.e. negative text-indent), but that seems like a lot of unnecessary work. Why wouldn’t I just use a regular HTML coded anchor?
<?php echo anchor(base_url(),''); ?>
Perhaps they thought that people would likely be passing in a blank string more by mistake than by design, I don't know and can't answer that part of your question.
Using the CodeIgniter anchor method in the URL helper has the advantage of automatically adding in your website's base path if necessary.
If you want to keep using the CodeIgniter helper and have anchors with no anchor text, you have several options:
Option 1: Add a space in the second argument:
<?php echo anchor(base_url(),' '); ?>
Option 2: Extend the URL helper and remove the behaviour:
Go into application\helpers and make a new file, called MY_url_helper.php
You can then put code in there to either replace the anchor method or define an entirely new method.
Here are some code examples of what you could put in the file: (I've adapted the code from the url_helper in a CodeIgniter installation I had handy)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('anchor_hide_text'))
{
function anchor_hide_text($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
}
or
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function anchor($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}

precontroller hooks in codeigniter

I am using pre-controller hook codeigniter in my project
Description:
we are using subdomain concept and three templates(theme). eg: My site is xyz.com. this is having one first template.
some business signup with this xyz site. for eg. abc(business). We create abc.xyz.com. abc chooses 2 template. abc.xyz.com in browser need to show 2nd template. It is not showing 2nd template. it is showing only 1st template.
When we clicked any link on the site more than once , then the template 2 is set for abc.xyz.com link.
I am using codeigniter. loaded session, database in autoload files.
I used precontroller hook to check whether the url is xyz or any subdomain abc.xyz.com
In hook i am setting template if the url is subdomain one.
But template is not showing when abc.xyz.com is in browser. when i refresh the url for some clicks or clicked any of the header link some count , it showing the actual template of the business abc.
Please help me to fix this issue or provide me some solution .
<?php
class Subdomain_check extends CI_Controller{
public function __construct(){
parent::__construct();
$this->CI =& get_instance();
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
}
function checking()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST']); //creates the various parts
if($subdomain_arr[0] == 'www')
{
$subdomain_name = $subdomain_arr[1]; //2ND Part
}
else
{
$subdomain_name = $subdomain_arr[0]; // FIRST Part
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
if( $subdomain_name != 'xyz' )
{
$where = array();
$where['subdomain_name'] = $subdomain_name;
$where['status'] = 1;
$this->db->from('subdomain_map');
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() < 1)
{
header('Location:http://xyz.com/index.php?/error');
}
else
{
$result = $query->row_array();
$this->CI->session->set_userdata('subdomain_id',$result['subdomain_id']);
$this->CI->session->set_userdata('subdomain_name',$result['subdomain_name']);
$org_id = gat_organisationid_using_subdomainid($result['subdomain_id']);
$this->CI->session->set_userdata('organisation_id', $org_id);
if($org_id)
{
$templ_id = get_templid_using_organisationid($org_id);
$org_logo = get_organisation_logo($org_id);
}
if($templ_id){
if($this->session->userdata('pinlogin'))
$this->CI->session->set_userdata('template_set', 4);
else
$this->CI->session->set_userdata('template_set', $templ_id);
}
if($org_logo)
$this->CI->session->set_userdata('org_logo', $org_logo);
}
}
else
{
$this->CI->session->unset_userdata('subdomain_id');
$this->CI->session->unset_userdata('subdomain_name');
if( $this->CI->session->userdata('user_id') && $this->CI->session->userdata('user_category')<=2 )
{
$this->CI->session->unset_userdata('organisation_id');
$this->CI->session->unset_userdata('org_logo');
}
}
}
}
Here is the basic check you need to support custom themes per subdomain
// Gets the current subdomain
$url = 'http://' . $_SERVER['HTTP_HOST'];
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
// store $host[0], which will contain subdomain or sitename if no subdomain exists
$subdomain = $host[0];
// check for subdomain
if ($subdomain !== 'localhost' OR $subdomain !== 'mysite')
{
// there is a subdomain, lets check that its valid
// simplified get_where using activerecord
$query = $this->db->get_where('subdomain_map', array('subdomain_name' => $subdomain, 'status' => 1));
// num_rows will return 1 if there was a valid subdomain selected
$valid = $query->num_rows() === 1 ? true : false;
if($valid)
{
// set theme, user_data, etc. for subdomain.
}
else
{
// get user out of here with redirect
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/error');
exit();
}
}
Note that when using subdomains with codeigniter, you should set your config > base_url to the following:
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/poasty/poasty-starterkit/';
this will ensure things like site_url() and other CI helpers still work.
Reading through your code may I suggest utilizing more of Codeigniters built-in functionality, for example your __construct function has a lot of un-necessary code:
Original code
public function __construct(){
parent::__construct();
/**
* CI already exists
* since this controller extends CI_controller, there is already and instance of CI available as $this.
$this->CI =& get_instance();
*/
/**
* duplicate check, CI checks if library is loaded
* and will ignore if loaded already
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
*/
$this->CI->load->library('session');
}
Optimized for Codeigniter
public function __construct()
{
parent::__construct();
$this->CI->load->library('session');
}
I suggest reading up on the Codeigniter user_guide to better understand what codeigniter can do. #see http://codeigniter.com/user_guide/
I hope you find this helpful!

How to access Magento from CodeIgniter?

I have a default CodeIgniter 2.1 install with Magento 10.4.4 installed in a subdir called store.
The following code works when run from web root (with .htaccess disabled). It will give the firstname, lastname of the logged in Magento user.
<?php
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
?>
But, if I run this in a CodeIgniter model, then isLoggedIn returns false.
Here is the CodeIgniter page:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
}
}
CodeIgniter is doing something that I have not been able to track yet. The websiteId is returned correctly, but isLoggedIn returns false.
Anyone have any ideas? THANKS!!
I use both but ive never tried to mash them like that. I foresee quite a few problems.
How are you patching into magento?
You might need two db connections running :
$db['magento']
$db['default'] // codeigniter default
Sessions could become a real problem here also aswell as config data.
Consider sticking with magento for now, then maybe patch into your blog/website via a RESTFul service.
Both code examples above work fine. The problem I had was calling session_start() near the top of the CodeIgniter index.php file. Once that was removed, it all started working.
For posterity, here is a Magento 10 Library for CodeIgniter 2.1:
application/libraries/magento.php
<?php if ( ! defined('BASEPATH')) exit("No direct script access allowed");
Class Magento {
function __construct($params)
{
global $site_root;
$name = $params['name'];
// Include Magento application
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
// Uncomment next line if you have moved app/etc
// $options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options=null);
return Mage::getSingleton("core/session", array("name" => $name));
}
}
// end of magento.php
Usage example app/model/test_mage.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
$params = array('name' => 'frontend'); // frontend or adminhtml
$this->load->library('magento', $params);
}
public function index()
{
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if ($session->isLoggedIn())
{
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}
else
$magento_message .= 'Guest!';
echo $magento_message . '<br>';
}
}
// end of test_mage.php

Resources