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

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>';
}

Related

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

Clear cache on CodeIgniter using wildcard

CodeIgniter documentation specified only two-ways to delete cache. They are:
$this->cache->delete('cache_item_id')
- for deleting individual cache thru ID
$this->cache->clean()
- for deleting ALL cache
My website have static and dynamic content and I would like to delete all the cache on the latter only.
I'm looking for something like ->delete("latest*") that will delete "latest-video", "latest-video-funny", "latest-video-music", "latest-article", etc.
I think I've got it working, calling $this->cache->cache_info(); will fetch a multidimensional array of all saved cache. The array keys inside the fetch array are the cache_item_id so I can just do the following.
$wildcard = 'latest';
$all_cache = $this->cache->cache_info();
foreach ($all_cache as $cache_id => $cache) :
if (strpos($cache_id, $wildcard) !== false) :
$this->cache->delete($cache_id);
endif;
endforeach;
There is a helper that does this, you can find it here.
how is cache created
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
.
.
.
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$CI->uri->uri_string();
$cache_path .= md5($uri);
helper itself
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('delete_cache'))
{
function delete_cache($uri_string)
{
$CI =& get_instance();
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$uri_string;
$cache_path .= md5($uri);
if (file_exists($cache_path))
{
return unlink($cache_path);
}
else
{
return TRUE;
}
}
}
all credits go to Steven Benner, his blog.
usage:
delete_cache('/blog/comments/123');

Flash messanger in zf2

How can i use flash messenger in zend freamwork 2? Session documentation is not yet. Anyone know it? But session libraries are there.
Update :
Zend Framework new release added FlashMessenger View Helper , found in path /library/Zend/View/Helper/FlashMessenger.php
FlashMessenger.php
Old answer :
I have written a custom view helper, for printing flash messages
In /module/Application/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'flashMessage' => function($sm) {
$flashmessenger = $sm->getServiceLocator()
->get('ControllerPluginManager')
->get('flashmessenger');
$message = new \My\View\Helper\FlashMessages( ) ;
$message->setFlashMessenger( $flashmessenger );
return $message ;
}
),
);
}
Create a custom view helper in /library/My/View/Helper/FlashMessages.php
namespace My\View\Helper;
use Zend\View\Helper\AbstractHelper;
class FlashMessages extends AbstractHelper
{
protected $flashMessenger;
public function setFlashMessenger( $flashMessenger )
{
$this->flashMessenger = $flashMessenger ;
}
public function __invoke( )
{
$namespaces = array(
'error' ,'success',
'info','warning'
);
// messages as string
$messageString = '';
foreach ( $namespaces as $ns ) {
$this->flashMessenger->setNamespace( $ns );
$messages = array_merge(
$this->flashMessenger->getMessages(),
$this->flashMessenger->getCurrentMessages()
);
if ( ! $messages ) continue;
$messageString .= "<div class='$ns'>"
. implode( '<br />', $messages )
.'</div>';
}
return $messageString ;
}
}
then simple call from layout.phtml , or your view.phtml
echo $this->flashMessage();
Let me show example of controller action
public function testFlashAction()
{
//set flash message
$this->flashMessenger()->setNamespace('warning')
->addMessage('Mail sending failed!');
//set flash message
$this->flashMessenger()->setNamespace('success')
->addMessage('Data added successfully');
// redirect to home page
return $this->redirect()->toUrl('/');
}
In home page, it prints
<div class="success">Data added successfully</div>
<div class="warning">Mail sending failed!</div>
Hope this will helps !
i have written a post about this some time ago. You can find it right here
Basically you use it just the same like earlier.
<?php
public function commentAction()
{
// ... display Form
// ... validate the Form
if ($form->isValid()) {
// try-catch passing data to database
$this->flashMessenger()->addMessage('Thank you for your comment!');
return $this->redirect()->toRoute('blog-details'); //id, blabla
}
}
public function detailsAction()
{
// Grab the Blog with given ID
// Grab all Comments for this blog
// Assign the view Variables
return array(
'blog' => $blog,
'comments' => $comments,
'flashMessages' => $this->flashMessenger()->getMessages()
);
}
Then in your .phtml file you do it like this:
// details.phtml
<?php if(count($flashMessages)) : ?>
<ul>
<?php foreach ($flashMessages as $msg) : ?>
<li><?php echo $msg; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Obviously this isn't all too handy, as you have to do this for every single .phtml file. Therefore doing it within the layout you have to do it at best like the following:
<?php
// layout.phtml
// First get the viewmodel and all its children (ie the actions viewmodel)
$children = $this->viewModel()
->getCurrent()
->getChildren();
$ourView = $children[0];
if (isset($ourView->flashMessages) && count($ourView->flashMessages)) : ?>
<ul class="flashMessages">
<?php foreach ($ourView->flashMessages as $fMessage) : ?>
<li><?php echo $fMessage; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
If you need further description, please see my blog, but i guess the code itself is pretty clear (apart frmo the layout.phtml example). Alternatively you're always free to write your own view helper to have it look a little cleaner inside your view-templates.
How to grab Flashmessenger’s messages in a View Helper – sharing code as requested by Sam.
The View helper should implement the ServiceManagerAwareInterface interface and related methods. The plugin will now have access to a Service Manager which we can use to get the Service Locator and ultimately access to the Flash Messenger.
I’ve not touched this code since I initially wrote it – so there may be a more elegant way of doing this.
protected function getMessages()
{
$serviceLocator = $this->getServiceManager()->getServiceLocator();
$plugin = $serviceLocator->get('ControllerPluginManager');
$flashMessenger = $plugin->get('flashmessenger');
$messages = $flashMessenger->getMessages();
// Check for any recently added messages
if ($flashMessenger->hasCurrentMessages())
{
$messages += $flashMessenger->getCurrentMessages();
$flashMessenger->clearCurrentMessages();
}
return $messages;
}
And calling getMessages() from within the plugin should return an array of messages that can be passed to a partial and rendered.
Add code below to the view to render error messages:
<?php echo $this->flashmessenger()
->setMessageOpenFormat('<div class="alert alert-danger"><ul%s><li>')
->setMessageCloseString('</li></ul></div>')
->render('error')
; ?>
In previous request, make sure you created an error message by running code below in your controller:
$this->flashmessenger()->addErrorMessage('Whops, something went wrong...');

Can't use session variable in routes.php file in codeigniter?

I am use following code to retrieve the session variable in routes.php
if($this->db_session->userdata('request_url')!="")
{
$route['user/(:any)'] = "search_user_name/redirect_url/".$_SESSION['request_url'];
$this->db_session->unset_userdata('request_url');
}
else {
$route['user/(:any)'] = "search_user_name/index/$1";
}
the session variable would be set into template/header.php
$this->db_session->set_userdata('request_url', $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
You can not use db_session in routes.php because routes.php is parsed before db_session is loaded.
Maybe you should create a base controller and redirect from the constructor of the base controller.
Correct me if iam wrong.
You can use hooks.
Codeigniter user guide hooks
You can use database in routes and put your routes url in database.
Here is an example:
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$table2 = $db->dbprefix.'lang';
$query2 = $db->get( $table2 );
$result2 = $query2->result();
foreach( $result2 as $row )
{
$fields = $db->list_fields($table2);
$findme = 'code';
foreach($fields as $field):
$pos = strpos($field, $findme);
if($pos !== false and $row->$field != ''):
$route[''.$row->$field.''] = 'main/setlang/$1';
endif;
endforeach;
}

CodeIgniter - Displaying and entering dynamic meta data

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);

Resources