Expert – CodeForest https://www.codeforest.net Sat, 30 Aug 2025 08:29:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.5 https://www.codeforest.net/wp-content/uploads/2017/06/cropped-Asset-3-32x32.png Expert – CodeForest https://www.codeforest.net 32 32 The Best Way to Filter Bad Traffic at the Edge: Cloudflare Workers Durable Objects https://www.codeforest.net/cloudflare-workers-durable-objects-scaling?utm_source=rss&utm_medium=rss&utm_campaign=cloudflare-workers-durable-objects-scaling https://www.codeforest.net/cloudflare-workers-durable-objects-scaling#respond Thu, 29 May 2025 16:04:42 +0000 https://www.codeforest.net/?p=2682 Read More »The Best Way to Filter Bad Traffic at the Edge: Cloudflare Workers Durable Objects]]> The Challenge

Cloudflare Workers Durable Objects helped us scale our API infrastructure to handle over 139 million monthly requests — while drastically reducing KV storage costs and improving response speed. In this post, we’ll walk you through exactly how we transitioned from KV and Cache API to Durable Objects, the mistakes we made, the numbers we tracked, and why DOs were the missing piece.

Our Laravel API (running on AWS) powers thousands of connected WordPress websites. These sites call various endpoints: for license checks, user-specific data, updates, and more.

But soon, we noticed something:

  • Fake or spoofed requests were hitting us.
  • Expired domains kept calling paid endpoints.
  • Our AWS load was rising — unnecessarily.

We needed a pre-check firewall layer, and that’s where Cloudflare Workers came in.

Using Cloudflare Workers to Filter Bad Traffic

Cloudflare Workers let us inspect every request at the edge — before it reached AWS. We used it to:

✅ Block requests missing the X-Customer-Domain header
✅ Require a valid Authorization token
✅ Verify the domain wasn’t on our expired list

This logic alone dropped a lot of noise.

The expired domains list lives in Cloudflare KV (key-value), updated by our Laravel app every 6 hours and during domain connection/disconnection.

But we ran into problems with Cloudflare KV scaling.

Attempt 1: Cloudflare Cache API

Why We Tried Cache API

We wanted to use Cloudflare Cache API inside Workers to store a parsed list of expired domains, reduce KV reads, and scale better.

Sample Code Using Cache API:

const EXPIRED_KEY = "expired:hub_expired_domains:latest";
const EXPIRED_TTL = 600;

async function getExpiredDomains(env) {
  const cache = caches.default;
  const cacheKey = new Request("https://internal/expired-domains");

  const cached = await cache.match(cacheKey);
  if (cached) return new Set(await cached.json());

  const version = await env.BLOCKLIST_KV.get(EXPIRED_KEY);
  const raw = await env.BLOCKLIST_KV.get(`expired:hub_expired_domains:${version}`);
  const parsed = JSON.parse(raw || "[]");

  const response = new Response(JSON.stringify(parsed), {
    headers: { "Cache-Control": `max-age=${EXPIRED_TTL}` }
  });
  ctx.waitUntil(cache.put(cacheKey, response.clone()));

  return new Set(parsed);
}

Why Cache API Failed

Despite expectations, Cloudflare Cache API wasn’t global. It works per Worker instance, meaning:

  • Instances didn’t share cached data
  • Every edge spun up its own empty cache
  • We still hit KV tens of thousands of times

After just 2 hours, we had 238K hot KV reads. At 139M monthly requests, this wasn’t sustainable.


Attempt 2: Cloudflare Durable Objects

What Are Durable Objects?

Cloudflare Durable Objects are a shared stateful object with memory that can be accessed by any Worker instance. They’re ideal when:

  • You need consistent data across edge locations
  • You want to reduce repeated storage reads

How We Used Durable Objects in Cloudflare Workers

We registered a Durable Object named ExpiryCache. This object:

  • Pulled the domain list from KV every 10 minutes
  • Stored it in memory
  • Allowed all Workers to call it

Sample Code to Check Expiration with Durable Object:

const id = env.EXPIRY_DO.idFromName("cache");
const obj = env.EXPIRY_DO.get(id);
const res = await obj.fetch(`https://internal/is-expired?id=${domain}`);
const { expired } = await res.json();

Why Durable Objects Worked

✅ Shared memory across instances
✅ Zero repeated parsing or JSON overhead
✅ KV reads dropped to a handful per day
✅ Massive cost savings

cloudflare workers
cloudflare workers

KV vs Cache API vs Durable Objects: What We Learned


Real Numbers & Pricing Impact

  • 139M monthly requests
  • KV read pricing: $0.50/million
  • That’s $70/month in reads only
  • After Durable Objects: almost $0 in reads

Plus, performance improved. Expired domain checks went from 20–50ms (KV) to 2–3ms (DO memory).

cloudflare workers vs durable objects vs cache api

Monitoring Cloudflare Worker + Durable Objects

Next, we plan to expose a /metrics route from our DO to:

  • Show total expired domains cached
  • Track last KV refresh timestamp
  • Count blocked expired requests

Conclusion: Why Cloudflare Workers with Durable Objects Matter

Cloudflare Workers are a game-changer for filtering edge traffic. But as you scale, the choice of Cache API, KV, or Durable Objects becomes critical.

We learned that:

  • Cloudflare KV is great for storage, not for high-frequency reads
  • Cache API works only within a single instance and isn’t scalable
  • Cloudflare Durable Objects offer a shared, consistent, scalable memory layer

If you’re running a high-volume API like ours — do yourself a favor and test Cloudflare Workers Durable Objects early.

]]>
https://www.codeforest.net/cloudflare-workers-durable-objects-scaling/feed 0
Custom post fields using Advanced Custom Fields WordPress plugin https://www.codeforest.net/wordpress-how-to-make-custom-post-field-using-advanced-custom-fields-plugin?utm_source=rss&utm_medium=rss&utm_campaign=wordpress-how-to-make-custom-post-field-using-advanced-custom-fields-plugin https://www.codeforest.net/wordpress-how-to-make-custom-post-field-using-advanced-custom-fields-plugin#comments Sun, 11 Dec 2011 21:34:40 +0000 https://www.codeforest.net/?p=1153 The time when WordPress was used mainly as a blog engine has passed and WordPress has become one of the most powerful Content Management Systems on the web because of using custom post fields.

Custom post types allows flexibility and give enormous power to WordPress. Usually, we use custom post types with built-in fields like excerpt, content editor, thumbnail etc.

But often, we need some special type of fields for dealing with customer wishes like date picker, relationships, file upload etc.

This is where Advanced Custom Fields plugin comes in.

Advanced custom post fields overview

The Advanced Custom Fields Plugin gives you the tools to create your own custom edit screens. It’s a must have for any WordPress developer. Custom post fields types include: Wysiwyg, text, textarea, image, file, select, checkbox, page link, post object, date picker, repeater …

Advanced Custom Fields Plugin provides a simple to use interface allowing you to create, edit, reorder and completely customize your edit screens.

With Advanced Custom Fields Plugin it is not only possible to create new fields, but to hide WordPress’s default fields as well.

Installing the plugin

Installation is the same as for any WordPress plugin

  1. Download Advanced Custom Fields plugin
  2. Upload ‘advanced-custom-fields’ to the ‘/wp-content/plugins/’ directory
  3. Activate the plugin through the ‘Plugins’ menu in WordPress
  4. You may be prompted for a Database Upgrade. This is necessary for ACF to function. Please backup your database and click the Upgrade button

Usage

Once the plugin is uploaded and activated, go to Settings and click on the Adv Custom Fields link and then “Add New”. You can then give a name to your new set of fields (for example “Columns”) and add as many types of custom fields as you want. Currently supported types are:

  • Text
  • Text area
  • WYSIWYG Editor
  • Image
  • File
  • Select
  • Checkbox
  • Radio Button
  • True / False
  • Page Link
  • Post Object
  • Relationship
  • Date Picker
  • Repeater (it costs $25)

Advanced Custom Fields interface is very intuitive and it is very simple to add custom fields groups and assign them to what ever you want. You can decide what Pages, Posts or Custom Post Types you want to have this new set of Custom Fields. For example, you could have all Pages, or all Posts, or only a specific page (for example Home), or all posts in a certain category:

Advanced Custom Fields options page

Advanced Custom Fields also lets you decide what other fields are available on the page. So you can remove the Content Editor, Slug, Author etc and control that and you new fields all from one place.

Advanced Custom Post Fields

Advanced Custom Fields API

Plugin also have a powerful API for dealing with your fields. For example, to display a field on the theme inside a loop:

[code lang=”php”]
<p><?php the_field(‘field_name’); ?></p>
[/code]

More about the API can be read on Plugin’s official documentation page.

Extending the plugin

Now, you may think that all this is enough. Well, for an average developer it should be. But, if you want to make some really cool types of fields, you can. That is the beauty of this powerful plugin.

I am going to show you how easy it is to make your own custom post field on a real life example. At the end of this tutorial, you can download custom post field type shown here.

The problem

Your customer wants to enter Events into WordPress and wants to select a location of the event by simply clicking on Google Map.

Making the Events custom post type

To make this work, we need a custom post type named Events in which our customer will enter data. First, let us see what data will be needed:

  • Title
  • Image
  • Description
  • Date
  • Time
  • Location – shown on Google Maps

Let’s begin by making this post type. Open your theme’s functions.php and enter this in:

[code lang=”php”]
function eventRegister()
{
$labels = array(
‘name’ => _x(‘Events’, ‘post type general name’),
‘singular_name’ => _x(‘Event’, ‘post type singular name’),
‘add_new’ => _x(‘Add New’, ‘portfolio item’),
‘add_new_item’ => __(‘Add New Event’),
‘edit_item’ => __(‘Edit Event’),
‘new_item’ => __(‘New Event’),
‘view_item’ => __(‘View Event’),
‘search_items’ => __(‘Search Events’),
‘not_found’ => __(‘Nothing found’),
‘not_found_in_trash’ => __(‘Nothing found in Trash’),
‘parent_item_colon’ => ”
);

$args = array(
‘labels’ => $labels,
‘public’ => true,
‘publicly_queryable’ => true,
‘show_ui’ => true,
‘query_var’ => true,
‘capability_type’ => ‘post’,
‘hierarchical’ => false,
‘menu_position’ => null,
‘supports’ => array(‘title’, ‘editor’, ‘thumbnail’),
‘rewrite’ => true,
‘show_in_nav_menus’ => true,
);

register_post_type(‘event’ , $args);
}

add_action(‘init’, ‘eventRegister’);
[/code]

Save functions.php and go to WordPress admin dashboard. You will see newly created Custom Post type in the left hand menu. Wow, that was easy.

Click on Add Event and you will see something similar to this:

Add events custom post type

You can enter title, description and thumbnail image. Now, open your Advanced Custom Fields under Settings and click Add new. We will add other fields into field group called Events and it should look like this:

Advanced custom fields - field group

If you go to Add Event page now, you should see that you can now pick an event date and enter a time.

Wow, that was really easy. Now comes the hard part.

Making our own custom field type

Author of this great plugin has made our lives easier and give us a Class template for making our own custom field types for ACF. Download it here, unpack it and place it inside your active theme. I prefer to create a fields folder in my theme’s root and put this template in it.

Now rename this file to location.php. Open it up in your editor and rename the class, the name variable and the title:

[code lang=”php”]
class Location_field extends acf_Field
{
function __construct($parent)
{
// do not delete!
parent::__construct($parent);

// set name / title
$this->name = ‘location’; // variable name (no spaces / special characters / etc)
$this->title = __("Location",’acf’); // field label (Displayed in edit screens)

} …
[/code]

Next, we must register this field so ACF plugin will know about it. Open your theme’s functions.php and enter this anywhere:

[code lang=”php”]
register_field(‘Location_field’, dirname(__FILE__) . ‘/fields/location.php’);
[/code]

This function will register our field in the ACF. It has 2 parameters, the first is our Class name and the second is the path to the Class file.

If you go to Advanced Custom Fields Settings, you should see Location in the drop down:

Location field in the drop down

Next thing we are going to do is create our Latitude and Longitude field that will be shown on edit screen and populated with values from Google Map.

For this, we will need create_field function inside our location.php file:

[code lang=”php”]
function create_field($field)
{
echo ‘<input type="text" value="’ . $field[‘value’] . ‘" id="’ . $field[‘name’] . ‘" class="’ . $field[‘class’] . ‘" name="’ . $field[‘name’] . ‘" />’;
echo ‘<div id="map"></div>’;
}
[/code]

Save this file and go add Location field to field group inside ACF settings and Update. Now, go to entering new Event and you will see our Location text field. Everything is working, field gets saved to database. Basically, we recreated the text field.

Adding Google Map

Next task is to add a Google Map and some Google Map API, so when the user clicks on the map, we will get the Latitude and Longitude of that point and fill our Location field with it.

For this use, we will use admin_head function, which is great for inserting CSS and JavaScript:

[code lang=”php”]
function admin_head()
{
?>
<style type="text/css">
#map {width: 100%; height: 500px; margin-top: 10px;}
</style>
<script src=’http://maps.googleapis.com/maps/api/js?sensor=false’ type=’text/javascript’></script>
<script type="text/javascript">
function load() {
var exists = 0, marker;
// get the lat and lng from our input field
var coords = jQuery(‘.location’).val();
// if input field is empty, default coords
if (coords === ”) {
lat = 45.77598686952638;
lng = 15.985933542251587;
} else {
// split the coords by ;
temp = coords.split(‘;’);
lat = parseFloat(temp[0]);
lng = parseFloat(temp[1]);
exists = 1;
}
// coordinates to latLng
var latlng = new google.maps.LatLng(lat, lng);
// map Options
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);

// if we had coords in input field, put a marker on that spot
if(exists == 1) {
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
draggable: true
});
}

// click event
google.maps.event.addListener(map, ‘click’, function(point) {
if (exists == 0) {
exists = 1;
// drawing the marker on the clicked spot
marker = new google.maps.Marker({
position: point.latLng,
map: map,
draggable: true
});
//put the coordinates to input field
jQuery(‘.location’).val(marker.getPosition().lat() + ‘;’ + marker.getPosition().lng());
// drag event for add screen
google.maps.event.addListener(marker, "dragend", function (mEvent) {
jQuery(‘.location’).val(mEvent.latLng.lat() + ‘;’ + mEvent.latLng.lng());
});
} else {
// only one marker on the map!
alert(‘Marker already on the map! Drag it to desired location.’);
}
});
//dragend event for update screen
if(exists === 1) {
google.maps.event.addListener(marker, "dragend", function (mEvent) {
jQuery(‘.location’).val(mEvent.latLng.lat() + ‘;’ + mEvent.latLng.lng());
});
}
}

jQuery(document).ready(function(){
load();
});
</script>

<?php
}
[/code]

There is plenty of comments above in the code, so everything is self explanatory.

When you go to add new Event, you will now see a Google Map below your Location field. When you click on a map, Lat and Long coordinates will be filled into your Location field. You can even drag a marker on a map to change the location! How cool is that?

Now, all we have to do is to show this Event in our theme, along with a Google Map.

Showing the location in the theme

Actually, it is very easy to show the coordinates we entered in our event in the theme. Advanced Custom Fields has a great API for that.

To use the coordinates, just enter this inside your WordPress loop:

[code lang=”php”]
the_field(‘location’);
[/code]

But, I want to show this coordinates in a map. So create a single-event.php file in your theme’s folder and enter something like this (this is just the content inside a single post loop for TwentyEleven Theme):

[code lang=”php”]
<div class="entry-content">
<?php the_content(); ?>
<p>Date of the event: <?php the_field(‘date’); ?> <?php the_field(‘time’); ?></p>
<div id="map" style="width: 500px; height: 350px;"></div>
<?php
$location = get_field(‘location’);
$temp = explode(‘;’, $location);
$lat = (float) $temp[0];
$lng = (float) $temp[1];
?>
<script src=’http://maps.googleapis.com/maps/api/js?sensor=false’ type=’text/javascript’></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
// coordinates to latLng
var latlng = new google.maps.LatLng(lat, lng);
// map Options
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
}
// call the function
load();
//]]>
</script>
<?php wp_link_pages( array( ‘before’ => ‘<div class="page-link"><span>’ . __( ‘Pages:’, ‘twentyeleven’ ) . ‘</span>’, ‘after’ => ‘</div>’ ) ); ?>
</div><!– .entry-content –>
[/code]

Or, you can make a page with events and one map that will show all your events. What ever you want, is achievable now.

Conclusion

WordPress is a very powerful tool and stuff described above, makes it even more powerful. Your imagination is the limit.

Demo
Don’t hesitate to share your thoughts or ask a question below.

]]>
https://www.codeforest.net/wordpress-how-to-make-custom-post-field-using-advanced-custom-fields-plugin/feed 25
Obfuscate your e-mail address with PHP, JavaScript and CSS https://www.codeforest.net/obfuscate-your-email-address-with-php-javascript-and-css?utm_source=rss&utm_medium=rss&utm_campaign=obfuscate-your-email-address-with-php-javascript-and-css https://www.codeforest.net/obfuscate-your-email-address-with-php-javascript-and-css#comments Thu, 27 Oct 2011 19:27:29 +0000 https://www.codeforest.net/?p=1089 Read More »Obfuscate your e-mail address with PHP, JavaScript and CSS]]> According to Wikipedia, more than 97% of all e-mails sent over the net are unwanted. That’s around 200 billion spam messages per day.

To keep this insane amount of spam out of your inbox, you should keep your e-mail safe when you display it on web. One of the ways to keep it safe is to obfuscate it. In this tutorial I’ll show you how to create a script that will do just that.

Basic requirements for such script (at least from my point of view) are:

  1. It should function pretty much out of the box. User should work only with real e-mail; script should obfuscate and deobfuscate it on the fly.
  2. It should show obfuscated e-mail to bots, but real one to humans; humans should not even notice that obfuscation (or deobfusaction) is taking place.
  3. Script should work on all desktop browsers (I’m talking IE6+here) and on mobile browsers as well (at least on the ones that support JavaScript).

To handle this, we’ll create a PHP function that will take string (e-mail address) as an argument. The function will reverse the address and obfuscate it using slightly modified ROT13 algorithm.

Deobfuscation will be done with JavaScript. When user opens the page we will detect which e-mail links have been obfuscated, apply reversed ROT13 algorithm on them and direction:rtl and unicode-bidi:override CSS rules.

This way, users will see real address, but spam bots will still (even if they can parse JavaScript) see a reversed e-mail.

This will, of course, leave us with a usability problem. If user copies the address, or if he clicks it, he’ll get the reversed one. Therefore, as a last deobfuscation step, we’ll reverse the reversed address and remove added CSS rules as soon as the user hovers over the link.

Demo

E-mail Obfuscation (PHP)

Code is thoroughly commented, have a look if you’d like to know more.

[code lang=”php”]
//Function takes string as an argument and returns a string.
function obfuscateEmail( $email ) {

//We will work with UTF8 characters, just to be safe that we won’t mess up any address.
$emailLetters = preg_split( ‘//u’, $email, null, 1 );
$obfuscatedEmail = ”;

//Reversing the string (e-mail).
$emailLetters = array_reverse( $emailLetters );

//Characters that are to be used when obfuscating email address.
//If you change this, make sure you change the characters string in JavaScript as well.
//And please note that the string must have even number of characters for this to work.
$characters = ‘123456789qwertzuiopasdfghjklyxcvbnmMNBVCXYLKJHGFDSAPOIUZTREWQ’;

//Get the number of characters dynamically.
$charactersLength = strlen( $characters ) – 1;

//Obfuscate string letter by letter.
foreach( $emailLetters as $letter ) {

//Get the current letter position in the string.
$letterPos = strpos($characters, $letter);

//If the character is present in our string of characters,
//we’ll switch it; if not, we’ll leave it as is.
if( $letterPos !== false ) {

$letterPos += $charactersLength / 2;

//For letters that are in our characters string positioned
//after the total number of characters, we’ll start from beginning.
//For example, “v” becomes “1”, “b” becomes “2”
$letterPos = $letterPos > $charactersLength ? $letterPos – $charactersLength – 1 : $letterPos;

//Obfuscated letter.
$newLetter = substr($characters, $letterPos, 1);

} else {

//Characters that aren’t in our list will be left unchanged.
$newLetter = $letter;

}

//We append obfuscated letter to the result variable.
$obfuscatedEmail .= $newLetter;

}

//Sign @ is a control letter. Since more than one @ sign is illegal
//in email address, we’re going to use two @ symbols to know when
//the string has been obfuscated (and needs deobfuscation).
//That way you can use obfuscated e-mail only in href attribute,
//while the link text can be something entirely different.
//An example: This is my email.
return $obfuscatedEmail . ‘@’;

}
[/code]

After you include function into your code, obfuscation can be preformed like this:

[code lang=”php”]

[/code]

And in a real life usage, you’d create an obfuscated e-mail link like this:

[code lang=”php”]
DemoSource files

Conclusion

With the amount of spam that is being sent over the internet, you surely don’t want to leave your e-mail address unattended; do everything you can to prevent it from falling in wrong (spammy) hands.

Technique that I’ve shown you here should be (if nothing else) at least a good start.

Additional readings:

]]>
https://www.codeforest.net/obfuscate-your-email-address-with-php-javascript-and-css/feed 5
Multilanguage support in Zend Framework https://www.codeforest.net/multilanguage-support-in-zend-framework?utm_source=rss&utm_medium=rss&utm_campaign=multilanguage-support-in-zend-framework https://www.codeforest.net/multilanguage-support-in-zend-framework#comments Mon, 05 Sep 2011 06:28:29 +0000 https://www.codeforest.net/?p=1003 We can not imagine a modern web application without a multi language support. I will show you how easy it is to setup usage of multiple languages in Zend Framework and how to setup some basic language routes (handy for SEO stuff).

The Zend Framework offers many ways for you to store your translated strings. It could be an array, a CSV or XML file or you could use gettext which we will be using today.

Why GetText?

There are many reasons I choose GetText. First, there is a handy program for editing GetText files called PoEdit (a bit on it later). So, when you have a handy program, it is easy to send it to translators, who do not have to mess with some arrays or XML files.

Second, Apache web server is caching the compiled .mo translation files, which is making them really fast.

Let’s start.

First you need an example application, it doesn’t need to be more complicated than a clean installation of ZF with an IndexController and a matching view, and of course the bootstrap.

So, open your Bootstrap.php file and add this method to the play:

[code lang=”php”]
protected function _initTranslate()
{
$translate = new Zend_Translate(‘gettext’,
APPLICATION_PATH . “/langs/”,
null,
array(‘scan’ => Zend_Translate::LOCALE_DIRECTORY));
$registry = Zend_Registry::getInstance();
$registry->set(‘Zend_Translate’, $translate);
$translate->setLocale(‘en’);
}
[/code]

So, what did we just do? We created the Zend_Translate object and pass in the directory containing all of our different languages. After that we saved our Zend_Translate object to the registry so we don’t need to create our object over and over again in our application.

Now, let’s go in our view and add some translations. Open up your index view and translate some strings that you find there:

[code lang=”php”]

translate(“Hello World!”); ?>

translate(“This is a Zend_Translate demonstration”); ?>

[/code]

Simply by using translate method in our view, all the GetText magic is going to happen later.

Now, go to PoEdit website and download PoEdit program and install it. Launch PoEdit.

Create a new catalog (File -> new catalog). Choose the language you want to translate the application to. We are going to use German, GERMANY and utf-8 for both character sets. Leave the plural forms blank.

On the paths tab, set the base path to the directory containing your application file, and add “.” as a path.

Click on the Keyword tab and add translate to keywords list. This way, we are telling PoEdit to scan for our translate methods.

Click OK and save a file in folder /application/langs/de_DE/LC_MESSAGES/ which you must create as messages.po.

Now, PoEdit does not scan PHTML files by default. So, go to Files — Preferences — Parser — PHP — Edit and add *.phtml on the list of extensions. Parser command line should look like this:

[code lang=”sql”]
xgettext –force-po -o %o %C %K %F -L php
[/code]

PoEdit will now automatically scan all source files inside the path you specified earlier and extract all strings that are passed to gettext() or _() or translate(). Click OK.

Now translate our two strings by clicking on them one by one and entering its german translation in lower box. Click Save. This will create messages.mo which will be used by our application later.

If you test the application now, it should be working and you should see default English strings displayed. That is because we set the Locale to en in our Bootstrap.php.

The idea is to have automatic routing of languages, so you won’t have to do it over and over again. So, open your Bootstrap.php again and insert our Routes in:

[code lang=”php”]
public function _initRoutes()
{
$this->bootstrap(‘FrontController’);
$this->_frontController = $this->getResource(‘FrontController’);
$router = $this->_frontController->getRouter();

$langRoute = new Zend_Controller_Router_Route(
‘:lang/’,
array(
‘lang’ => ‘de’,
)
);

$defaultRoute = new Zend_Controller_Router_Route(
‘:controller/:action’,
array(
‘module’=>’default’,
‘controller’=>’index’,
‘action’=>’index’
)
);

$defaultRoute = $langRoute->chain($defaultRoute);

$router->addRoute(‘langRoute’, $langRoute);
$router->addRoute(‘defaultRoute’, $defaultRoute);
}
[/code]

Now, the changing of Locale and translation strings are done in our Controller Plugin. So create one:

[code lang=”php”]
class App_Controller_Plugin_Language
extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$lang = $request->getParam(‘lang’, null);

$translate = Zend_Registry::get(‘Zend_Translate’);

if ($translate->isAvailable($lang)) {
$translate->setLocale($lang);
} else {
$translate->setLocale(‘en’);
}

// Set language to global param so that our language route can
// fetch it nicely.
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->setGlobalParam(‘lang’, $lang);
}
}
[/code]

This plugin is pretty trivial, you can play with it as you like, you can add COOKIE or SESSION support or whatever you like.

Now, back to our Bootstrap.php to init the plugin:

[code lang=”php”]
protected function _initLanguage()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new App_Controller_Plugin_Language());
}
[/code]

Now, test you application with ‘en’ or ‘de’ suffixes (myapp.home/de or myapp.home/en). You should see the transaltion is working perfectly.

Have you got any suggestions to improve this tutorial? Any new ideas for translating content with Zend Framework?

]]>
https://www.codeforest.net/multilanguage-support-in-zend-framework/feed 6
jQuery Mobile Advanced Tutorial – RSS reader app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-advanced-tutorial-rss-reader-app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app#comments Tue, 23 Aug 2011 06:59:38 +0000 https://www.codeforest.net/?p=970 Today’s tutorial is going to show you how you can use jQuery Mobile with PHP, MySQL and a bit of AJAX to build a small mobile web application.

At the end of this tutorial you will know how to add new RSS feed name and url into the database, how to delete the record from the database, how to fetch and parse a RSS feed and show its results inside jQuery Mobile list view.

If you are not familiar with jQuery Mobile, I suggest you read my jQuery Mobile basic tutorial and then come back.

So, let’s start. Many things in our RSS reader application will take place inside our index.php file. The front page of the application will have links for creating new RSS feed and Read existing feeds.

First of all we need a database table to store our feeds in. Create one using this SQL code:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
[/code]

Now, I will create a db.php which will have a database connection and some basic functions for database handling. Create folder named inc and put your db.php file in it with this code pasted:

[code lang=”php”]
/*** mysql hostname ***/
$hostname = ‘localhost’;

/*** mysql username ***/
$username = ‘root’;

/*** mysql password ***/
$password = ”;

$dbname = ‘demo’;

try
{
mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
}
catch (Exception $e)
{
// normally we would log this error
echo $e->getMessage();
}

function db_select_list($query)
{
$q = mysql_query($query);
if (!$q) return null;
$ret = array();
while ($row = mysql_fetch_array($q, MYSQL_ASSOC)) {
array_push($ret, $row);
}
mysql_free_result($q);
return $ret;
}

function db_select_single($query)
{
$q = mysql_query($query);
if (!$q) return null;
$res = mysql_fetch_array($q, MYSQL_ASSOC);
mysql_free_result($q);
return $res;
}
[/code]

This is a pretty basic code for connecting and fetching records from our database.

To keep things organized, I will put my header section inside external PHP file. Inside inc folder create file named header.php, then paste this in the header file:

[code lang=”php”]




Codeforest jQuery Mobile Tutorial



[/code]

This is basic HTML 5 header with included jQuery and jQuery Mobile.

Now create a file in your root directory and name it index.php and paste this in it:

[code lang=”php”]

Welcome!

CodeForest



[/code]

Save everything and try it in your browser. Pretty cool.

As you can see our links to other pages look like anchor links. I am going to have multiple pages inside my index.php file and that is the way to link to them.

Now paste this whole code inside index.php overwriting the previous code:

[code lang=”php”]

Welcome!

CodeForest

Add New RSS Feed

Back



Codeforest

RSS Feeds

Back

CodeForest



[/code]

Above code is pretty simple. There are 3 pages, the indexPage, addFeedPage and readFeedPage. As we firstly have to add some feeds to read, let me show you how to do it.

As you can see, the AddNewFeedPage is basically a form for collecting New feed data (Feed name and Feed URL). Open your index.php in browser and click on Create New Feed link. You should see the form.

Now, add this JavaScript code directly before the closing body tag in your index.php file:

[code lang=”javascript”]

[/code]

Above code is catching Submit button click event and making an AJAX call to addFeed.php file which will handle the database writing. Create an addFeed.php file and paste this in:

[code lang=”php”]
getMessage();
}
[/code]

We are including our database file, sanitizing user input (you should never trust user entered data and always sanitize it!) and finally writing our entry in database. Now, go and add your RSS feed and save it. Make sure the feed URL is correct.

Now go back to your home page and click on Read RSS feeds link. You should see a feed name you just entered. Let me show you how to fetch and parse this feed.

Create a file named feed.php in your root directory and paste this in:

[code lang=”php”]
feedData.php in your root folder and paste this in:

[code lang=”php”]




[/code]

This code is rendering the view. First we check if feed is valid and if it is parsing it using SimpleXMLElement. Go ahead and try it. If everything worked, you should see 10 titles from the feed which are links to the actual articles.

If something is wrong with the feed format and it is not in RSS feed format, you will get a nice message.

Notice the Delete button on top right. It is used so you can delete the feed you are viewing from the database. Create deleteFeed.php and paste the code for deleting in:

[code lang=”php”]

I hope that this tutorial showed how easy it is to build mobile web applications using jQuery Mobile, PHP and MySQL.

Do you like jQuery Mobile? Are you using it or plan to use it? Do not hesitate to discuss in our comment section below. And if you have any questions, I will gladly answer them.

Stay tuned.

]]>
https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app/feed 11
Android JSON-RPC client and PHP Zend Framework server https://www.codeforest.net/android-json-rpc-client-and-php-zend-framework-server?utm_source=rss&utm_medium=rss&utm_campaign=android-json-rpc-client-and-php-zend-framework-server https://www.codeforest.net/android-json-rpc-client-and-php-zend-framework-server#comments Mon, 11 Jul 2011 19:25:08 +0000 https://www.codeforest.net/?p=895 XML-RPC rules, but the amount of data it generates is its big disadvantage. This is where JSON-RPC steps in. Data it generates is significally smaller, but this isn’t suprising as JSON is known as fat free XML.This articles is based on my earlier Android XML-RPC article. Its PHP code and Zend Framework setup will be used so you should go through it if you haven’t earlier (at least as far as XMLRPC Android client chapter).

JSON-RPC PHP Server

We’ll start with adding additional actions to our server controller (with zf tool) – zf create action json Server. Lets open our Server controller (application/controllers/Server.php) and start building JSON-RPC server in our newly created json action.

[code lang=”php”]
public function jsonAction()
{
$this->_helper->viewRenderer->setNoRender();

$server = new Zend_Json_Server();
$server->setClass(‘Application_Model_Data’, ‘cf’);

if (‘GET’ == $_SERVER[‘REQUEST_METHOD’]) {
$server
->setTarget(‘http://localhost/xmlrpc-test/public/server/json’)
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();

header(‘Content-Type: application/json’);
echo $smd;
return;
}

echo $server->handle();
}
[/code]

First, we disable view rendering, instantiate Zend_Json_Server and attach a class which will responde to client calls Application_Model_Data.

Zend_Json_Server listens only for POST requests (but fortunately most JSON-RPC client implementations will only POST requests) so we have to check if our request is POST or GET. In GET request we can serve SMD (http://groups.google.com/group/json-schema/web/service-mapping-description-proposal) specification which provides service metadata to service consumers.

Take note of $server->setTarget method, it adds our server URL to specification. Modify it to suit your setup.

JSON-RPC PHP Client

Now its time to create PHP client for the purpose of testing our server. Unfortunately, Zend Framework currently (version 1.11) doesn’t have JSON-RPC client. Version 2.0 should have one, but until then we have to use some 3rd party client. Simplest to implement is jQuery JSON-RPC client specifically made for Zend Framework, you can download it here – http://www.tanabi.com/projects/jsonrpc.

From downloaded archive we extract contents of js directory and place it into public/js directory (we have to create js directory).

Lets again use zf tool and create json client action – zf create action json Client.

Our newly created action should look like this:

[code lang=”php”]
public function jsonAction()
{
$this->view->serverUrl = ‘http://localhost/xmlrpc-test/public/server/json’;
}
[/code]

Its pretty straitforward, we only forward server URL to view script. Now, lets modify view script created (application/views/scripts/client).

[code lang=”html”]
<html>
<head>
<?php
echo $this->headScript()
->appendFile($this->baseUrl(‘/js/jquery-1.3.min.js’))
->appendFile($this->baseUrl(‘/js/json2.js’))
->appendFile($this->baseUrl(‘/js/jquery.zend.jsonrpc.js’));
?>
<script type="text/javascript">
$(document).ready(function() {
var testClient = jQuery.Zend.jsonrpc({
url : ‘<?php echo $this->serverUrl; ?>’
});
var data1 = testClient.cf.test();
if (” != data1) {
$(‘#result1’).html(data1);
}
});
</script>
</head>
<body>
<div id="result1"></div>
</body>
</html>
[/code]

First, we add JS scripts (jquery-1.3.min.js, json2.js and jquery.zend.jsonrpc.js) then invoke jQuery and in line 11 we instantiate jQuery JSON-RPC client. In line 12 we call our RPC test method.

We are ready to test our JSON-RPC server. When we visit http://localhost/xmlrpc-test/public/client/json (at least in my setup) we should get results like this:

Capture j1

Yeah, it says XMLRPC but just because we haven’t change our Application_Model_Data class method. If we have similar looking results then we’re done with PHP part. Now, onto the Android part.

JSON-RPC Android Client 

Create new Android project and download Android JSON-RPC lib from http://code.google.com/p/android-json-rpc/. In eclipse, right click your project in package explorer and select properties. In properties select Java Build Path -> Add external JARs and navigate to downloaded .jar file.

captures2

Don’t forget to add internet permission to Android manifest file – open AndroidManifest.xml and in raw XML view add next line just before closing manifest tag:

<uses-permission android:name=”android.permission.INTERNET”></uses-permission>

In our example we’ll be using default layout file res/layout/main.xml but we’ll add an ID to its TextView element so that we can fill it out with received data. So open res/layout/main.xml file and locate TextView element. Add an android.id attribute with @+id/text_view value to it:

[code lang=”xml”]
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;LinearLayout xmlns:android=&amp;quot;http://schemas.android.com/apk/res/android&amp;quot;
android:orientation=&amp;quot;vertical&amp;quot; android:layout_width=&amp;quot;fill_parent&amp;quot;
android:layout_height=&amp;quot;fill_parent&amp;quot;&amp;gt;
&amp;lt;TextView android:id=&amp;quot;@+id/text_view&amp;quot; android:layout_width=&amp;quot;fill_parent&amp;quot;
android:layout_height=&amp;quot;wrap_content&amp;quot; android:text=&amp;quot;Hello&amp;quot; /&amp;gt;
&amp;lt;/LinearLayout&amp;gt;
[/code]

Lets start building our client. Open created activity (in src directory, com.cf.jsonrpc package), mine is called Client.

[code lang=”java”]
public class Client extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.text_view);
}
}
[/code]

In onCreate method we create reference to TextView element of our layout where we’ll display our results. Now lets create a method which will call our JSON-RPC server.

[code lang=”java”]
private String testMethod() {
JSONRPCClient client = JSONRPCClient
.create(&amp;quot;http://10.0.2.2/xmlrpc-test/public/server/json&amp;quot;);
String string = &amp;quot;&amp;quot;;
try {
string = client.callString(&amp;quot;cf.test&amp;quot;);
} catch (JSONRPCException e) {
Log.i(&amp;quot;JSON-RPC Client&amp;quot;, e.toString());
}
return string;
}
[/code]

First, we create and initialize JSONRPCClient and give it our server URL. As you can see we are using 10.0.2.2 address to access our own local web server. 127.0.0.1 or localhost is used by the underlying linux OS on emulator.

We’re using try-catch block to catch errors and deal with them. In try block we are calling our cf.test method. To JSONRPCClient we are telling that we expect a string to be returned (client.callString).

After creating this method we have to call it from onCreate method and display its return value to TextView element. Our modified Client activity class should look like this:

[code lang=”java”]
public class Client extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.text_view);
tv.setText(testMethod());
}

private String testMethod() {
JSONRPCClient client = JSONRPCClient
.create(&amp;quot;http://10.0.2.2/xmlrpc-test/public/server/json&amp;quot;);
String string = &amp;quot;&amp;quot;;
try {
string = client.callString(&amp;quot;cf.test&amp;quot;);
} catch (JSONRPCException e) {
Log.i(&amp;quot;JSON-RPC Client&amp;quot;, e.toString());
}
return string;
}
}
[/code]

Lets test this method on our emulator. Select Run->Run configurations and create new Android application configuration for our project and run it. Emulator screen should look similar to this:

Capturej2

If your result equals mine then you have running Android JSON-RPC client.

testMethod is pretty simple, lets upgrade it a bit.

[code lang=”java”]
private String getDataMethod(int numRows)
{
JSONRPCClient client = JSONRPCClient.create(&amp;quot;http://10.0.2.2/xmlrpc-test/public/server/json&amp;quot;);
String string = &amp;quot;&amp;quot;;
try {
JSONArray items = client.callJSONArray(&amp;quot;cf.getData&amp;quot;, numRows);
for (int i = 0; i &amp;lt; items.length(); i++) {
try {
JSONObject item = items.getJSONObject(i);
string = string + item.getString(&amp;quot;number&amp;quot;) + &amp;quot;. &amp;quot; + item.getString(&amp;quot;title&amp;quot;) + &amp;quot; – &amp;quot; + item.getString(&amp;quot;datetime&amp;quot;) + &amp;quot;\n\n&amp;quot;;
} catch (JSONException e) {
Log.i(&amp;quot;JSON-RPC Client&amp;quot;, e.toString());
}
}
} catch (JSONRPCException e) {
Log.i(&amp;quot;JSON-RPC Client&amp;quot;, e.toString());
}
return string;
}
[/code]

You can see that in line 6 of getDataMethod we tell our client that we expect JSON Array (JSON Object in some other cases could be used). In for loop we are iterating through this JSON array, creating JSON objects for array elements and pulling its data out.

Next step is to switch method calls in onCreate method:

[code lang=”java”]
textView.setText(testMethod());
[/code]
with this one:

[code lang=”java”]
textView.setText(getDataMethod(12));
[/code]
Save and run this configuration again. You should get similar result to this:

Capture j3

That’s it! We’ve covered everything, from PHP JSON-RPC server to Android client.

JSON-RPC vs. XML-RPC

Reason for writting was to check if and how much is JSON-RPC better than XML-RPC. My results are pretty conclusive.

My test procedure was pretty simple. I’ve run getData method on both JSON-RPC and XML-RPC, both of them returned simple data row (200 rows) – ordinal number, ‘Codeforest.net’ string and current date & time (Y-m-d H:i:s format).

Generated JSON data was 14kB, XML data was 52kB. This information alone was enough to convince me that  JSON-RPC was better. While using mobile network connection we should care for single byte, let alone 3x difference.

Second series of test was to determine who is faster. Both in method request-response cycle (combined with iterating through data) and in iterating through returned data alone. JSON-RPC’s method cycle (combined with iterating) was around 2.100ms while XML-RPC’s was 8.700ms. Iteration through data was around 1.200ms for JSON-RPC and around 6.000ms for XML-RPC. Difference in this test is even bigger, around 4x.


Although, my tests were simple and many different parameters affected the results, I think that it certainly shows that JSON-RPC is far better remote procedure than XML-RPC. What do you think?

]]>
https://www.codeforest.net/android-json-rpc-client-and-php-zend-framework-server/feed 1
How to build PHP XML-RPC Server, Client and Android application https://www.codeforest.net/how-to-build-php-xml-rpc-server-client-and-android-app?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-php-xml-rpc-server-client-and-android-app https://www.codeforest.net/how-to-build-php-xml-rpc-server-client-and-android-app#comments Wed, 23 Mar 2011 20:31:38 +0000 https://www.codeforest.net/?p=789 In this article I will show how to build PHP XML RPC server and how to consume provided services with PHP and an Android application as a client. PHP side of things will be built on top of Zend Framework and for Android will be using very thin XML RPC library android-xmlrpc ( http://code.google.com/p/android-xmlrpc/ ).

Assumption is that you already have downloaded Zend Framework and have Android SDK set up (as well as Android emulator). I’ll be using Eclipse both for PHP and Android development. Also, I’ll be using ZF tool for creating project, controllers and models.
We’ll start with building XMLRPC server component.

XMLRPC server component

In your web server’s document root run zf tool with this command: zf create project xmlrpc-test. Afterwards step into this newly created directory xmlrpc-test.

Now we’ll create needed controllers and models.

First run zf create controller Server (which creates our ServerController), then we’ll create our model zf create model Data. Because we’ll also create client side of XMLRPC lets create this controller now to finish out work with zf tool: zf create controller Client.

We should test if our website is running properly, go to http://localhost/xmlrpc-test/public with your browser and you should see image similar to the one below.

zend_framework

Now we’re ready to create our project in Eclipse, open PHP workspace, and go to File->New->PHP project, enter xmlrpc-test as a project name and click Finish. Our project is ready and all files created earlier are in it.

Eclipse - create new project

Lets open our Server controller (application/controllers/Server.php) and start building XMLRPC server.

[code lang=”php”]
class ServerController extends Zend_Controller_Action
{
public function indexAction()
{
$this->_helper->viewRenderer->setNoRender();

$server = new Zend_XmlRpc_Server();
$server->setClass(‘Application_Model_Data’, ‘cf’);

echo $server->handle();
}
}

[/code]

First, we disable our view. We instantiate Zend_XmlRpc_Server and add class which will respond to calls from client, this will be our Application_Model_Data class and we will set its namespace as cf.

We echo the servers handle method, and voila, our very simple and basic XMLRPC server is done.

Now let’s open our model (application/models/Data.php) and create some test method for returning dummy data.

[code lang=”php”]
class Application_Model_Data
{
/**
* Test method
*
* @return string
*/
public function test()
{
return ‘Hello XMLRPC!’;
}
}
[/code]

This class, Application_Model_Data is classic PHP class, the most important thing here is to notice the comments. They are mandatory, because when call occurs, Zend_XmlRpc_Server will be doing reflection of this class before running it, checking if called method exists and if its arguments are matching defined ones and are correct type. So, we have to define types of all input parameters (none in this test method) as well as method return type.

Let’s write XML RPC client to check if everything is OK so far.

XMLRPC PHP client

Earlier we created ClientController class (located in application/controller/Client.php) with default indexAction method and now we’ll add our code in it.

[code lang=”php”]
class ClientController extends Zend_Controller_Action
{
public function indexAction()
{
$client = new Zend_XmlRpc_Client(‘http://localhost/xmlrpc-test/public/server/’);
try {
$data = $client->call(‘cf.test’);
$this->view->data = $data;
} catch (Zend_XmlRpc_Client_HttpException $e) {
require_once ‘Zend/Exception.php’;
throw new Zend_Exception($e);
} catch (Zend_XmlRpc_Client_FaultException $e) {
require_once ‘Zend/Exception.php’;
throw new Zend_Exception($e);
}
}
}
[/code]

First we instantiate Zend_XmlRpc_Client and provide its constructor URI of our XML RPC server. Then we try to make a call to a test method (‘cf’ is a namespace defined for our Application_Model_Data class). We’ll forward returned data to our view.

Our view is located in application/views/scripts/client/index.phtml. In it we are only echoing data returned from our test method.

[code lang=”php”]

Via XMLRPC

escape($this->data); ?>
[/code]

If we run http://localhost/xmlrpc-test/public/client in our browser we should get something like this:

XML-RPC client result in browser

Let’s add another method to our Application_Model_Data class which will be expecting single Integer parameter and it will be returning an associative array.

[code lang=”php”]
/**
* Fetches data
*
* @param integer $num
* @return array
*/
public function getData($num)
{
$data = array();

for ($a = 0; $a < $num; $a++) { $data[] = array( 'title' => ‘Codeforest.net’,
‘number’ => $a + 1,
‘datetime’ => date(‘Y-m-d H:i:s’)
);
}

return $data;
}
[/code]

Method is called getData (yes, very creative) and it’s pretty simple. Again, notice the comments with defined @param and @return lines.

We also have to upgrade our ClientController class and instead of calling cf.test method will be calling cf.getData method. We only have to supstitute one line (7th):

[code lang=”php”]
$data = $client->call(‘cf.test’);
[/code]

with this one:

[code lang=”php”]
$data = $client->call(‘cf.getData’, 15);
[/code]

Everything else in the ClientController class stays the same.

We have to update our view script with something like this:

[code lang=”php”]

Via XMLRPC

data) > 0):?>

    data as $row):?>

  • escape($row[‘number’])?> – escape($row[‘title’])?>, escape($row[‘datetime’])?>


[/code]

Again, we go to our browser to test http://localhost/xmlrpc-test/public/client. Result is similar to:

xml-rpc-result

This concludes our PHP and Zend Framework part of the article.

XMLRPC Android client

If using Eclipse switch to Android workspace (File->Switch Workspace, pick your Android workspace).

After you have switched workspace go to File->New->Android Project, enter project name, select build target and fill the rest of the properties.

eclipse android project

Download Android XML-RPC client library from http://code.google.com/p/android-xmlrpc/.

Create new package in our project (right mouse click on project name in Package explorer and select New->Package). Name this package org.xmlrpc.android and copy files form archive directory android-xmlrpc/src/org/xmlrpc/android into this newly created package.

Eclipse-package

Now our directory structure should be similar to picture below:

directory-structure

Because we’ll be needing internet connection (to connect to our XML-RPC server) we need to add internet permission to our android manifest file. Open AndroidManifest.xml and in raw XML view add next line just before closing manifest tag:

[code lang=”xml”]

[/code]

In our example we’ll be using default layout file res/layout/main.xml but we’ll add an ID to its TextView element so that we can fill it out with received data. So open res/layout/main.xml file and locate TextView element. Add an android.id attribute with @+id/text_view value to it:

[code lang=”xml”]




[/code]

Now we can start building our Android Client. Open Client.java in our com.cf.xmlrpc package and enter:

[code lang=”java”]
public class Client extends Activity {

private XMLRPCClient client;
private URI uri;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

uri = URI.create(“http://10.0.2.2/xmlrpc-test/public/server/”);
client = new XMLRPCClient(uri);

TextView textView = (TextView) findViewById(R.id.text_view);
}
}
[/code]

First, we create class variables which will hold our XMLRPC Client and URI for our server. We can access this variables throughout our class.

In onCreate method we assign our uri variable URI object. As you can see we are using 10.0.2.2 address to access our own local web server. 127.0.0.1 or localhost is used by the underlying linux OS on emulator.

Then we create our XMLRPCClient and give its constructor our uri variable.

We’ll also get reference to TextView element of our layout where we’ll display our results.

If Eclipse is signaling for some error due to not having imported needed classes press Ctrl+Shift+O, this will import all needed classes automatically.

Next, we’ll create method which will call test method on our XML-RPC server (built earlier with Zend Framework).

[code lang=”java”]
private String testMethod() {
String text = “”;
try {
text = (String) client.call(“cf.test”);
} catch (XMLRPCException e) {
Log.w(“XMLRPC Test”, “Error”, e);
text = “XMLRPC error”;
}
return text;
}
[/code]

We’re using try – catch block to catch errors and to deal with them. After creating this method we have to call it from onCreate method and display its return value to TextView element. Our modified Client activity class should look like this:

[code lang=”java”]
public class Client extends Activity {

private XMLRPCClient client;
private URI uri;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

uri = URI.create(“http://10.0.2.2/xmlrpc-test/public/server/”);
client = new XMLRPCClient(uri);

TextViewtextView = (TextView) findViewById(R.id.text_view);
textView.setText(testMethod());
}

private String testMethod() {
String text = “”;
try {
text = (String) client.call(“cf.test”);
} catch (XMLRPCException e) {
Log.w(“XMLRPC Test”, “Error”, e);
text = “XMLRPC error”;
}
return text;
}
}
[/code]

We are ready to test our Android client. Select Run->Run configurations and create new Android application configuration for our project:

Creating-run-conf

After the emulator boots up we should have something similar to this:

Android emulator

Hoorah! Our Android client is using our XML RPC web service!

Lets now create method which will call our other server function getData.

[code lang=”java”]
private String getDataMethod(int num) {
String text = “”;
try {
Object[] data = (Object[]) client.call(“cf.getData”, num);
for(Object o: data) {
HashMap map = (HashMap) o;
text = text + “‘datetime’ => ” + map.get(“datetime”) + “, ‘number’ => ” + map.get(“number”) + “, ‘title’ => ” + map.get(“title”) + “\n\n”;
}
} catch (XMLRPCException e) {
Log.w(“XMLRPC Test”, “Error”, e);
text = “XMLRPC error”;
}
return text;
}
[/code]

Method we are calling (cf.getData) expects one parameter (integer) and returns an associative array (from PHP’s perspective). In Java we received array with map items.

If you are having trouble figuring out what your custom XML RPC service is returning you be sure to check out great post at Inchoo. It describes how to parse the data returned from XMLRPC.

Next step is to switch method calls in onCreate method:

[code lang=”java”]
textView.setText(testMethod());
[/code]

to this one:

[code lang=”java”]
textView.setText(getDataMethod(12));
[/code]

After saving and running (again select Run->Run configurations) our changed Android client we should have on the emulator something like:

Android working XML-RPC


And that’s it. We covered all the elements necessary to build PHP XML-RPC Server, Client and Android application that will harvest it.

Feel free to leave a comment, a question or a critique. Also feel free to request a follow up or an article with stuff that interests you.

]]>
https://www.codeforest.net/how-to-build-php-xml-rpc-server-client-and-android-app/feed 27
Multiple virtual hosts in WAMP https://www.codeforest.net/multiple-virtual-hosts-in-wamp?utm_source=rss&utm_medium=rss&utm_campaign=multiple-virtual-hosts-in-wamp https://www.codeforest.net/multiple-virtual-hosts-in-wamp#comments Wed, 22 Dec 2010 22:30:17 +0000 https://www.codeforest.net/?p=698 Virtual hosting is a method for hosting multiple domain names on a computer using a single IP address. This allows one machine to share its resources, such as memory and processor cycles, to use its resources more efficiently. This is often found on shared hosting servers.

Developers often have loads of web sites under www or htdocs folder which are then accessed on daily basis. To be able to use absolute paths in your applications, some people change the documentroot variable in httpd.conf to current working directory. This allows them to access this page with just http://localhost.

But, it isn’t efficient because you have to change the variable manually, restart Apache, and it just takes to much time.

We can use Virtual hosts on Windows to deal with this problem. As I am using WAMP server for development, this tutorial will explain how to do it in WAMP, but other products are very similar, so you want have problems porting this.

First lets edit the windows hosts file located in C:\Windows\system32\drivers\etc\hosts. Open up the file in your favorite text editor and add a line like this:

[code lang=”html”]
127.0.0.1 mydomain.home
[/code]

Basically, this tells Windows to resolve IP 127.0.0.1 (which is localhost) to mydomain.home. Save the file and close it.

Next we want to edit our httpd.conf file and httpd-vhosts.conf file. So first browse to C:\wamp\bin\apache\apache2.2.11\conf and open up httpd.conf in your favorite text editor. Then scroll down to the bottom. Look for this line:

[code lang=”html”]
#Include conf/extra/httpd-vhosts.conf
[/code]

Uncomment it (remove the # symbol in the beginning of the line). Save the file and exit. Now browse just one more folder down the tree to C:\wamp\bin\apache\apache2.2.11\conf\extras and open the httpd-vhosts.conf in your favorite text editor. Now scroll to the bottom and add this code:

[code lang=”html”]

ServerAdmin webmaster@localhost
DocumentRoot “c:/wamp/www”
ServerName localhost
ErrorLog “logs/localhost-error.log”
CustomLog “logs/localhost-access.log” common


DocumentRoot “c:/wamp/www/your-local-folder”
ServerName mydomain.home

Options Indexes FollowSymLinks
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1


[/code]

There are two directives for Virtual Host. First one is preserving our localhost, so you can still access the WAMP dashboard. The second one is actually telling Apache where to look when someone requests mydomain.home . Rest of the entry is allowing you to use .htaccess on this domain.

Restart Apache server.

Now, you should be able to use http://mydomain.home to develop and test your site. Whenever you need to add new site just add new entry in Windows hosts file and copy last Virtual host entry in httpd-vhosts.conf and change the domain and path.

Now you know how to add Virtual Hosts under WAMP.

]]>
https://www.codeforest.net/multiple-virtual-hosts-in-wamp/feed 13
Anonymous or lambda functions in PHP https://www.codeforest.net/anonymous-or-lambda-functions-in-php?utm_source=rss&utm_medium=rss&utm_campaign=anonymous-or-lambda-functions-in-php https://www.codeforest.net/anonymous-or-lambda-functions-in-php#comments Mon, 22 Nov 2010 09:31:41 +0000 https://www.codeforest.net/?p=658 Originally published Nov 22, 2010. Updated for PHP 7.4–8.3+.

Examples work on PHP 5.3+, but sections below mention newer features (PHP 7.4 arrow functions, PHP 8.1 first-class callables)

Wikipedia says: In computing, an anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.

In PHP the terms ‘anonymous function’ and ‘closure’ are used almost interchangeably. Anonymous functions are implemented by the Closure class; a closure is an anonymous function that can capture variables from the surrounding scope.

Sounds pretty complicated.

I will start with showing some interesting example of, so called, variable functions in PHP. It means that if we append parenthesis to a variable, then PHP will look for a function with the same name as to whatever the variable evaluates to and try to execute it.

OMG, this really sound complicated. Let me show you:

function Test($var) {
    echo "This is $var";
}

This is very simple function. We can now call this function indirectly using a variable which value is the same as the function name:

$f = "Test";
$f("variable function");

The above code will output This is variable function. This PHP functionality is the reason that using double quotes is slower then single quotes, as you can see in my PHP Mythbusters article.

We can use it in OOP as well, as seen in the php.net example:

<?php
declare(strict_types=1);

final class Foo
{
    public function variable(): void
    {
        $name = 'bar';

        if (method_exists($this, $name) && is_callable([$this, $name])) {
            $this->{$name}(); // calls bar()
        } else {
            throw new BadMethodCallException("Method {$name}() not found or not callable.");
        }
    }

    public function bar(): void
    {
        echo 'This is bar';
    }
}

$foo = new Foo();
$funcName = 'variable';
$foo->{$funcName}(); // calls $foo->variable()

This is an interesting concept that can be used to implement callbacks, function tables, and so forth.

Dynamic calls like $this->$name() are powerful but risky if $name can come from user input. Prefer validating with method_exists()/is_callable() or pass callables as [$object, 'method'].”
Then end with a forward link: “Modern alternatives: Closure::fromCallable() and first-class callable syntax

Now let me try to explain an anonymous function. We have this code:

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, function ($v) { return $v > 2; });

function ($v) { return $v > 2; } is the lambda function definition. We can even store it in a variable, so it can be reusable:

$max = function ($v) { return $v > 2; };

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, $max);

Now, what if you want to change the maximum number allowed in the filtered array? You would have to write another lambda function or create a closure (PHP 7+):

<?php
declare(strict_types=1);

$greaterThan = function (int $max): Closure {
    return function (int $v) use ($max): bool {
        return $v > $max;
    };
};

$input  = [1, 2, 3, 4, 5];
$output = array_filter($input, $greaterThan(2));      // keeps 3,4,5 (keys preserved)
$output = array_values($output);                       // optional: reindex to [3,4,5]

print_r($output);

A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called. They come from the functional programming world, where there are a number of concepts in play. Closures are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined.

Here is a simpler example of PHP closure:

$string = "Hello World!";
$closure = function() use ($string) { echo $string; };

$closure();

Variables to be imported from the outside environment are specified in the use clause of the closure function definition. By default, they are passed by value, meaning that if we would update the value passed within the closure function definition, it would not update the outside value. We can, however, do this by prefacing the variable with the & operator, which is used in function definitions to indicate passing by reference. Example:

$x = 1
$closure = function() use (&$x) { ++$x; }

echo $x . "";
$closure();
echo $x . "";
$closure();
echo $x . "";

You see the closure is using the outside variable $x and incrementing it each time the closure is called. We can mix variables passed by value and by reference easily within the use clause, and they will be handled without any problem.

As we saw in the examples for lambda functions, one of the most obvious uses for closures is in the few PHP functions that accept a callback function as a parameter. Closures, however, can be useful in any context where we need to encapsulate logic inside its own scope.

The real beauty of closures is that it avoids polluting the global namespace with a function that is used only once. As soon as the variable falls out of scope it, and the closure contained in it is destroyed.

]]>
https://www.codeforest.net/anonymous-or-lambda-functions-in-php/feed 1