laravel, php, Uncategorized

Custom Facades in Laravel 4.2.X


// file System

Untitled

 

 

 

 

 

 

 

 

 

 




Name of Custom Facade "Sky"

steps:

1. create a new folder facades inside app folder

2. create a new folder same name as of your custom facade name. [ eg: app/facades/Sky / ]

3 create one more folder inside app / [ your facade folder ] / Facade

4. now create 2 files in the your facade base

app/facades/Sky/
              / Helper.php
              / HelperServiceProvider.php

5. a facade class inside a
app/facades/Sky/Facade/
                     /Helper.php

=============== Contents inside files =================
## app/facades/Sky/Helper.php

namespace Sky;
Class Helper {

	public function fire()
	{
		return 'Fireing ... ';
	}

	public function boom()
	{
		return 'Fireing boom... ';
	}
}

## app/facades/Sky/HelperServiceProvider.php

namespace Sky;
use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {



    public function register()
    {
        // Registering 'helper class'
        $this->app['helper'] = $this->app->share(function($app)
        {
            return new Sky\Helper;
        });

        // dynamic creating Alias, so that you do not have to add an Alias in app/config/app.php
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('SkyHelper', 'Sky\Facade\Helper');
        });
    }

}
?>
## app/facades/Sky/Facade/Helper.php

namespace Sky\Facade;

use Illuminate\Support\Facades\Facade;

class Helper extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'Sky\Helper'; }

}

### this is it all you need for your custom facades ##########

### one more last thing you need to do for autoload the facade classes ####
# GO to composer.json, add new line app/facades for autoloading.

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/facades",
			"app/tests/TestCase.php"
		]
	},

finally RUN " composer dump-autoload "

Cheers enjoy
laravel, php

changing mac’s default php setting to xamp [ enabling mcrypt in mac lion]


To those that uses XAMPP 1.7.3 and Mac

  1. Go to Terminal
  2. Enter which php
    • If it says /usr/bin/php, then proceed to 3.
  3. Enter sudo nano ~/.bash_profile
  4. then paste this export PATH="/Applications/XAMPP/xamppfiles/bin:$PATH"
  5. ctrl – O then enter to save, then ctrl – X to exit.
  6. restart terminal.
  7. Enter which php
    • If you did it right, it should be the same as the path in #4.

The reason for the mcrypt error is because your mac uses it’s native php, you need to change it to the one xampp has.

Some of useful commands to test php settings in mac lion

>> which PHP  // to see if mac is using default php server or third party php setting [ xamp or mamp ]

>> php –version  // to see the php version

>> php -m  // to see the active modules / extensions

 

 

Reference : http://stackoverflow.com/questions/16830405/laravel-requires-the-mcrypt-php-extension

 

ajax, JavaScript, jquery

live updating select option with chosen


If you guys have ever used chosen plugin. you might have end up trying dynamically changing selection option with javascript.
Here is code below, that you can update option dynamically with javascript for chosen plugin.

 

<select name="names" id="names" >
    <option value="1"> Niraj </option>
    <option value="2" >Buddha</option>
    <option value="3">Dino</option>
    <option value="4">AL</option>
</select>

$("#name").chosen();

// updating again with javascript
document.getElementById('names').value = 4;
$('#names').trigger('liszt:updated');
mysql, php

Import CSV data into to MySQL database


Import CSV to MySQL

A simple in-built command to import whole CVS data to mysql database

1 LOAD DATA LOCAL INFILE 'd:\\\my_file.csv'
2 into TABLE table_name
3 FIELDS TERMINATED BY ','
4 LINES TERMINATED BY '\n'
5 (field1,field2,field3)

Note:
table column should be as tat of cvs file

“\\\” is important, keep it as it is just change ur file name.

 

after importing data you may found there is some extra quote in the fileds (“) you can remove it via following script

// I am using Codeigniter active record pattern hope you guys get the concept.

function read()
{

// get the data from table
$res = $this->db->select()->get(‘tbl_states_details’)->result();
$cnt = 0;

// loop it
foreach($res as $key => $val):
$cnt++;
// filter ” to null space or nothing
$data[‘suburb’] = str_replace(‘”‘,”,$val->suburb);
$data[‘postcode’] = str_replace(‘”‘,”,$val->postcode);
$data[‘state’] = str_replace(‘”‘,”,$val->state);
$data[‘dc’] = str_replace(‘”‘,”,$val->dc);
$data[‘type’] = str_replace(‘”‘,”,$val->type);
$data[‘lat’] = str_replace(‘”‘,”,$val->lat);
$data[‘lon’] = str_replace(‘”‘,”,$val->lon);
$id = $val->id;
// update the row again
$this->update_again($data,$id );

endforeach;

}

function update_again($data, $id){
$this->db->where(‘id’,$id)->update(‘tbl_states_details’,$data);
}

ajax, JavaScript, php

country list arrray php/json


$options["AF"] = "Afghanistan";  
$options["AX"] = "Åland Islands";  
$options["AL"] = "Albania ";  
$options["DZ"] = "Algeria ";  
$options["AS"] = "American Samoa";  
$options["AD"] = "Andorra";  
$options["AO"] = "Angola ";
$options["AI"] = "Anguilla ";
$options["AQ"] = "Antarctica ";
$options["AG"] = "Antigua and Barbuda ";
$options["AR"] = "Argentina";
$options["AU"] = "Australia ";
$options["AT"] = "Austria ";
$options["AZ"] = "Azerbaijan";
$options["BS"] = "Bahamas ";
$options["BH"] = "Bahrain ";
$options["BD"] = "Bangladesh ";
$options["BB"] = "Barbados ";
$options["BY"] = "Belarus";
$options["BE"] = "Belgium ";
$options["BZ"] = "Belize ";
$options["BJ"] = "Benin ";
$options["BM"] = "Bermuda ";
$options["BT"] = "Bhutan";
$options["BO"] = "Bolivia ";
$options["BA"] = "Bosnia and Herzegovina ";
$options["BW"] = "Botswana ";
$options["BV"] = "Bouvet Island ";
$options["BR"] = "Brazil";
$options["IO"] = "British Indian Ocean Territory ";
$options["BN"] = "Brunei Darussalam ";
$options["BG"] = "Bulgaria ";
$options["BF"] = "Burkina Faso ";
$options["BI"] = "Burundi";
$options["KH"] = "Cambodia ";
$options["CM"] = "Cameroon ";
$options["CA"] = "Canada ";
$options["CV"] = "Cape Verde ";
$options["KY"] = "Cayman Islands ";
$options["CF"] = "Central African Republic ";
$options["TD"] = "Chad ";
$options["CL"] = "Chile ";
$options["CN"] = "China ";
$options["CX"] = "Christmas Island";
$options["CC"] = "Cocos (Keeling) Islands ";
$options["CO"] = "Colombia ";
$options["KM"] = "Comoros ";
$options["CG"] = "Congo ";
$options["CD"] = "Congo, the Democratic Republic of the";
$options["CK"] = "Cook Islands ";
$options["CR"] = "Costa Rica ";
$options["CI"] = "Côte D'Ivoire";
$options["HR"] = "Croatia ";
$options["CU"] = "Cuba ";
$options["CY"] = "Cyprus ";
$options["CZ"] = "Czech Republic ";
$options["DK"] = "Denmark";
$options["DJ"] = "Djibouti ";
$options["DM"] = "Dominica ";
$options["DO"] = "Dominican Republic ";
$options["EC"] = "Ecuador ";
$options["EG"] = "Egypt";
$options["SV"] = "El Salvador ";
$options["GQ"] = "Equatorial Guinea ";
$options["ER"] = "Eritrea ";
$options["EE"] = "Estonia ";
$options["ET"] = "Ethiopia ";
$options["FK"] = "Falkland Islands (Malvinas) ";
$options["FO"] = "Faroe Islands ";
$options["FJ"] = "Fiji ";
$options["FI"] = "Finland ";
$options["FR"] = "France";
$options["GF"] = "French Guiana ";
$options["PF"] = "French Polynesia ";
$options["TF"] = "French Southern Territories ";
$options["GA"] = "Gabon ";
$options["GM"] = "Gambia ";
$options["GE"] = "Georgia ";
$options["DE"] = "Germany ";
$options["GH"] = "Ghana ";
$options["GI"] = "Gibraltar ";
$options["GR"] = "Greece";
$options["GL"] = "Greenland ";
$options["GD"] = "Grenada ";
$options["GP"] = "Guadeloupe ";
$options["GU"] = "Guam ";
$options["GT"] = "Guatemala";
$options["GG"] = "Guernsey ";
$options["GN"] = "Guinea ";
$options["GW"] = "Guinea-Bissau ";
$options["GY"] = "Guyana ";
$options["HT"] = "Haiti";
$options["HM"] = "Heard Island and Mcdonald Islands ";
$options["VA"] = "Holy See (Vatican City State) ";
$options["HN"] = "Honduras ";
$options["HK"] = "Hong Kong ";
$options["HU"] = "Hungary";
$options["IS"] = "Iceland ";
$options["IN"] = "India ";
$options["ID"] = "Indonesia ";
$options["IR"] = "Iran, Islamic Republic of ";
$options["IQ"] = "Iraq ";
$options["IE"] = "Ireland ";
$options["IM"] = "Isle of Man ";
$options["IL"] = "Israel ";
$options["IT"] = "Italy ";
$options["JM"] = "Jamaica";
$options["JP"] = "Japan ";
$options["JE"] = "Jersey ";
$options["JO"] = "Jordan ";
$options["KZ"] = "Kazakhstan ";
$options["KE"] = "KENYA";
$options["KI"] = "Kiribati ";
$options["KP"] = "Korea, Democratic People's Republic of ";

echo json_encode($options);
php

integrating elFinder file manager with CKEditor


url: https://github.com/Studio-42/elFinder/wiki/Integration-with-CKEditor
 

Integration with CKEditor

Configure CKEditor to use the elFinder file manager

You must tell CKEditor where the file manager is.

Method 1 – during init

CKEDITOR.replace( 'editor1', {
    filebrowserBrowseUrl : 'path/to/editor/file', // eg. 'includes/elFinder/elfinder.html'
    uiColor : '#9AB8F3'
});

Method 2 – by editing the config.js file

CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
    config.filebrowserBrowseUrl = 'includes/elFinder/elfinder.html';
};

Update the elFinder page being called by CKEditor

Edit elfinder.html to get next code

<script type="text/javascript" charset="utf-8">
    // Helper function to get parameters from the query string.
    function getUrlParam(paramName) {
        var reParam = new RegExp('(?:[\?&]|&amp;)' + paramName + '=([^&]+)', 'i') ;
        var match = window.location.search.match(reParam) ;

        return (match && match.length > 1) ? match[1] : '' ;
    }

    $().ready(function() {
        var funcNum = getUrlParam('CKEditorFuncNum');

        var elf = $('#elfinder').elfinder({
            url : 'php/connector.php',
            getFileCallback : function(file) {
                window.opener.CKEDITOR.tools.callFunction(funcNum, file);
                window.close();
            },
            resizable: false
        }).elfinder('instance');
    });
</script>

Discussion

http://elfinder.org/forum/#/20110728/integration-with-ckeditor-759177/

Other HOWTOs

http://forrst.com/posts/Elfinder_2_0_beta_filemanager_for_the_web_Ex-PPS
http://elfinder.org/forum/#/20120619/ckeditor-3-1700374/

php

40+ Must-Bookmark PHP Classes & Libraries For Developing Faster


reference:

http://www.webresourcesdepot.com/40-must-bookmark-php-classes-libraries-for-developing-faster/

 

PHP, being the most popular scripting language, has lots of documentation, tutorials and resources about itself.

And, as a feature-rich language, it is possible to accomplish many tasks by default from handling e-mails to images, PDFs to database connections, etc.

However, there are high-quality and free PHP classes and libraries which helps you get more like:

  • good looking charts
  • form validation
  • parsing feeds
  • better image or database handling
  • and more.

Here is a collection 40+ totally free PHP classes and libraries that every PHP developer would love to bookmark:

Free PHP Classes And Libraries

Content


BackPress

A complete library, that grew from WordPress, which offers the most common tasks for creating web applications like user management, HTTP transactions, logging, formatting and more.

PHP User Class

The class aims to ease the handling of user management tasks like registration, login, logout, etc. for PHP-MySQL applications.

 

phpSEO

Do you want to automate the process of generating keywords or meta tags from the content? This is what  phpSEO does.

It can create any desired number of keywords from a given string or URL, generate a description and does all with not using any banned words you define.

PHP Typography

PHP class for improving web typography with features like hyphenation, spacing control, wrapping of long text, character replacement for items like ordinal suffixes, trademark or math symbols and more.

Tag Cloud

The class creates tag clouds from a given array of items where each tag can have its own color, URL and style.

 

Handling Documents


PHPExcel

A set of PHP classes for writing to and reading from different file formats, like Excel, PDF and HTML.

It supports many MS Excel features like adding worksheets to a spreadsheet, inserting data and formulas to cells, calculating formulas and much more.

PHPPowerpoint

Set of classes for reading and writing to Powerpoint documents and supports adding slides, rotating images and more.

TCPDF

A complete PHP PDF class with features like custom page formats or margins, support for images and automatic page header/footer management.

It can also handle document encryption, PDF annotations, bookmarks and table of content.

FPDF

A PDF generator class with flexible page format and margins support. It can automatically arrange page breaks and can insert images into documents.

ZipStream

Compared to many PHP zipping libraries, this class does not require  “writable temp directory” and can generate + start the download after the client timeouts (good for huge files).

 

File Uploads, Images & Colors


EasyUp

A clean and simple PHP file upload class which can also delete the file uploaded and get the size + filename of it

class.upload.php

PHP class for manipulating and uploading image files on-the-fly.

It can convert, resize and work on uploaded images in many ways: add labels, watermarks and reflections.

Image Resizing Made Easy with PHP

A PHP class which can open, resize (smart resizing with no distortion) and save a number of images in multiple formats.

It is explained very well with a detailed tutorial.

WideImage

A feature-rich PHP library for image manipulations by providing a simple way to loading and saving images from/to files, strings, database, uploads and URL addresses.

You can apply filters, get channels, merge, resize, crop or rotate images using the library.

Asido

A powerful PHP image processor with features like resize, rotate, watermak, frame, convert, rotate, crop and much more.

xColor

An impressive class to make various calculations on colors like converting between formats (HEX,RGB,HSL/HSV), getting the end color when a color is added to or removed from a pallette and more.

Article Sponsor: Admin Templates, a professional XHTML back-end template, is offering a huge discount to WebResourcesDepot readersAdmin Templates

 

E-mail


PHPMailer

One of the most popular PHP e-mail classes around with features like multiple receivers, embedded images, HTML or plain text,  SMTP authentication and much more.

There are also other projects by the same author for form-to-emails, mailing list and bounce management.

Swift Mailer

The library can send emails using SMTP, sendmail, postfix or a custom method.

It supports SMTP authentication, handling attachments and much more. A great thing is, it is extendable with plugins (there are already ones for antiflood, throttling and logging).

 

Forms


PHP Validation

A set of rules for instantly adding server-side validation to our forms.

The rules include “required, length, e-mail, date, numeric, string and much more. Also, you can add custom regular expressions.

VDaemon

It can check user input by comparing to the rules defined and, if necessary, display errors.

The library has methods like required, e-mail, zip codes, IP address, date, time, integer, string and much more.

Securimage (Captcha)

This PHP captcha class can create complex images or captcha codes and can be easily added into existing forms.

The codes generated can be in custom length, font and use backgrounds. Also, a Flash button can play the mp3 of the image.

 

Database & Backup


Crystal

This PHP database wrapper offers a human-readable SQL and makes CRUD operations so easy.

It also handles data validation and database manipulation (creating databases, tables, etc.)

ADOdb

database abstraction library for PHP which supports almost any database (MySQL, PostgreSQL, Interbase, Firebird, Informix, Oracle, MSSQL, Access, SQLite, etc.).

It is fast, supports advanced features like SQL code generation, database-backed sessions and more.

Doctrine

It offers a powerful database abstraction layer with many features for database schema introspection, schema management and PDO abstraction.

Also an object relational mapper (ORM) that sits on top of a powerful database abstraction layer (DBAL) which can write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL) providing developers a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.

ezSQL

This PHP database class makes using popular databases a breeze.ezSQL with detailed debug functions to find outwhat’s going on in your SQL code.

NYT_Transformer

A free PHP class that is developed by the NY Times development team.

It can convert various input types to many other types like Oracle to MySQL or from a database to a flat file.

PHPMYExport (Database Backup)

The class enables users to backup and restore databases (MySQL, PostgreSQL, MSSQL, etc.) from a web-based interface.

BigDump (Staggered MYSQL Database Importer)

Taking backups of large MySQL databases via scripting (like from phpMyAdmin) is usually an issue as backups may not be completed because of the PHP timeout value.

This class backups databases with small portions every time and continues from where it had stopped.

Database CSV Class

It extracts data from a database and generates a .CSV file with it.

The class can be set to prompt you to download the generated file or save it in a folder (or both).

 

Charts


pChart

PHP charts class for displaying the data beautifully.

It supports line- bar and pie charts in both 2D and 3D.

JpGraph

An impressive graphing library with support for lots of chart types. It generates web-friendly, small images, can draw 200+ flags with a built-in function and has an internal caching.

Sparkline PHP Graphing Library

Sometimes charts are not what we need and displaying the data within a paragraph, just like a word, works better.

This library exactly does that. Using it, you can create tiny graphics to present your data.

 

Feeds


SimplePie

It is the ultimate PHP class for fetching, caching, parsing feeds with lots of integrated methods from social bookmarking integration to one-click subscriptions for popular feed services.

Last RSS

A simple yet powerful RSS parser with features like caching, limiting items and date formatting.

Magpie RSS

A modular and bandwidth-friendly (transparent GZIP-encoding) RSS parser with an integrated caching system.

 

3rd Party Services


Short URL Class

There are many sort URL services and it is possible that you may not want to stick to only one.

This class can shorten URLs with TinyURL, Is.gd, Hex.io, Tr.im & Bit.ly API.

Google Translation PHP wrapper

Google Translate has a limit of translating 5000 words at once. This smart PHP class can translate unlimited numbe of words by splitting the input, sending the queries one-by-one and merging the results at the end.

GAPI – Google Analytics PHP Interface

An easy to use PHP class for getting Google Analytics data.

To view a working demo, check out the tutorial I had published using the class: FeedCount-Like Google Analytics Counter.

PHP Payment Library for Paypal, Authorize.net and 2Checkout (2CO)

If you want to use these providers at the same time in a project, the library offers an API which enables you to handle all providers in the same way.

phpFlickr

It is a PHP wrapper for the Flickr API which returns a friendly array of data to make development easier.

The class has support for uploading photos, getting albums + images inside them and caching.

Twitter with OAuth class

It makes communicating with the Twitter API (using OAuth) easier and supports almost every feature of the API.

PHPWeatherLib

A lightweight weather conditions library that pulls the weather data from the NOAA’s public XML weather feeds.

It can get the temperature (in multiple formats), wind, humidity and an icon for the weather situation.

 

Others


HTML Purifier

A complete PHP HTML filter library that can remove malicious code (with a whitelist) and also makes sure the documents are standards-compliant.

PHP DNS Query

A set of PHP classes that provides a direct domain name service API.

It offers direct to-server queries, the ability to process the response in detail but still with a simple interface for the developer.

hKit (Microformats Parser)

A simple class for extracting common microformats from a page (currently supports hCard).

XMPPHP

It enables you to connect to any XMPP 1.0 server (like Google Talk), send messages and supports SSL/TLS connections.

ajax, JavaScript, jquery, Uncategorized

returning value from jquery ajax api


.responseText is used to return the value with ajax api

check_title_exist : function(_title){

return $.ajax({
url: base_url+”themes/theme_title_exist/”,
data:{title:_title},
cache: false,
type:’POST’,
async: false
}).responseText;
}

//php part

function theme_title_exist(){
$title = $this->input->post(‘title’, TRUE);
if($this->themes_model->check_theme_title_exit($title)):
echo ‘true’;
else:
echo ‘false’;
endif;
}

/// java script view part

res = themes_mod.check_title_exist(ni_gui.get_value(_post_data,’title’));

if(res == ‘true’){
alert(1)
}else{
alert(0)
}