rss

CakePHP Paginate Count with group by

1

Category : General, PHP

I am working on a CakePHP project these days, today i ran into a different problem with CakePHP. Sometimes i feel that there are small-small things that are sometimes missed by the Cake developers, but thank God that there are some workarounds available to them.  Here is the problem statement that i encountered, i had a table in which i was having duplicate records and i wanted to show only distinct records in the data grid which was using the CakePHP paginator class to create a paginated data grid.

Now to show only the distinct rows i used the group by clause to eliminate the duplicate records, the records were coming fine but when i saw the paging it was not working right at all. The problem was that the paginator’s “paginateCount” function was also considering the “Group By” clause while doing the counting of the total records. This was crazy.

I searched through Google to get a solution to that and found this link, where people have already reported a his error to the cake developers. The solution that worked for me was that i needed to override the “paginateCount” function and use a different function in my model to get the correct number of total records. I added this function to my model and whola it worked for me. Here is the function that needs to be added model to get things right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
		$parameters = compact('conditions', 'recursive');
 
		if (isset($extra['group'])) {
			$parameters['fields'] = $extra['group'];
 
			if (is_string($parameters['fields'])) {
				// pagination with single GROUP BY field
				if (substr($parameters['fields'], 0, 9) != 'DISTINCT ') {
					$parameters['fields'] = 'DISTINCT ' . $parameters['fields'];
				}
				unset($extra['group']);
				$count = $this->find('count', array_merge($parameters, $extra));
			} else {
				// resort to inefficient method for multiple GROUP BY fields
				$count = $this->find('count', array_merge($parameters, $extra));
				$count = $this->getAffectedRows();
			}
		} else {
			// regular pagination
			$count = $this->find('count', array_merge($parameters, $extra));
		}
		return $count;
	}
  • Share/Bookmark

CakePHP Sharing sessions between apps on the same domain

Category : General, PHP

Few days back i was working on two separate CakePHP applications, suddenly there was a need to maintain session between these two separate apps working on the same domain. Let me explain a bit more.

Cake-logo
Cake-logo
Image via Wikipedia

I was having two apps (i)wishlist (ii) lighthouse

These are two separate apps under the root folder having the directory structure as:
/htdocs
/wishlist
/app
/config
….
/lighthouse
/app
/config ….

By default the sessions are created relative to the apps directory, and this was the problem i was dealing with, not a big thing but i spent a lot of time figuring this, but for you its will work like a charm.

Steps that i follow to make the two apps share sessions between them.
1. Edit “core.php” for wishlist and the lighthouse and add the line
ini_set(‘session.cookie_path’, “/”);
This is to direct the CakePHP app to create the session on the root

2. The Session.cookie name should be same for the two apps

3. The Session.salt should be same for the two apps

4. Security.level should be low in both the apps

This is it what is required. Let me know if you are still stuck with the things, happy coding.

  • Share/Bookmark

PHP: Fuzzy Address Matching Algo (Levenshtein)

Category : MySQL, PHP

Few days back i encountered a weird problem.
I had three tables in my DB viz: students, sites, company. Student table has the address fields and a column named “site_id” to connect it to the sites table. Sites table also has its address fields.

Now the challenge was to update the “site_id” field of the students table based on the matching address in the student and the site table. The address fields in both the tables were divided into following fields

  • address1
  • address2
  • city
  • state
  • country
  • zip

Now i had to think of a solution of how to do it. After googling a while i found a function called “levenshtein()” in PHP. This function calculated the distance between two given strings, bingo i got an idea and implemented the sddress matching algorithm. I have attached the file with this post.
Kindly let me if that was helpful to you.

Download the code from here -> fuzzy-match

  • Share/Bookmark

Facebook: HipHop for PHP

Category : PHP, Technology

Facebook officially announced the project, titled HipHop, this morning and confirmed that it would be released as open source this evening.

Facebook has been working on a PHP compiler that will increase speed by around 80% and offer a just-in-time (JIT) compilation engine that will offer a number of advantages.

Less CPU means fewer servers, which means less overhead. This project has had a tremendous impact on Facebook

HipHop for PHP isn’t technically a compiler itself, it is a source code transformer. HipHop programmatically transforms your PHP source code into highly optimized C++ and then uses g++ to compile it.

HipHop executes the source code in a semantically equivalent manner and sacrifices some rarely used features — such as eval() — in exchange for improved performance.

HipHop includes a code transformer, a reimplementation of PHP’s runtime system, and a rewrite of many common PHP Extensions to take advantage of these performance optimizations.

You can read more about HipHop here

  • Share/Bookmark

Facebook Technology Tasting – HipHop for PHP

Category : PHP

  • Share/Bookmark

CakePHP – Pagination Sorting on 2 Columns

Category : PHP

I was just wondering how one can sort on two columns at the same time through CakePHP framework. It was a need for one om project and i was using whole lot of other components and helpers along with pagination, so i found a way out for doing this.

Here is my solution to the problem.
The way to do it is inject the second sort column into the passed argument array before calling the $this->paginate function. So here is what i did.


$this->mergeSortParameters(array(“xyz.firstname”=> ($this->passedArgs['direction'])? $this->passedArgs['direction'] : ‘asc’));

Here is the function that needs to be called before calling the paginate method


  1. //Function to merge all the sorting parameters
  2. function mergeSortParameters($sort_extras){
  3. $sortParams = array();
  4. if( isset($this->passedArgs["sort"]) ) {
  5. // Use merge of sort request and extras
  6. $sortParams = am( $sort_extras, array($this->passedArgs["sort"] => $this->passedArgs["direction"]));
  7. } elseif( isset( $this->paginate['order'] ) ) {
  8. // Use default sort
  9. $sortParams = $this->paginate['order'];
  10. }
  11. $this->passedArgs = array( ‘order’ => $sortParams, ‘keywords’ => $this->passedArgs['keywords']);
  12. }
  • Share/Bookmark

PHP Custom DateFiff Function

Category : PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
  /*
    $interval can be:
    yyyy - Number of full years
    q - Number of full quarters
    m - Number of full months
    y - Difference between day numbers
      (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
    d - Number of full days
    w - Number of full weekdays
    ww - Number of full weeks
    h - Number of full hours
    n - Number of full minutes
    s - Number of full seconds (default)
  */
 
  if (!$using_timestamps) {
    $datefrom = strtotime($datefrom, 0);
    $dateto = strtotime($dateto, 0);
  }
  $difference = $dateto - $datefrom; // Difference in seconds
 
  switch($interval) {
    case 'yyyy': // Number of full years
      $years_difference = floor($difference / 31536000);
      if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
        $years_difference--;
      }
      if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
        $years_difference++;
      }
      $datediff = $years_difference;
      break;
    case "q": // Number of full quarters
      $quarters_difference = floor($difference / 8035200);
      while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
        $months_difference++;
      }
      $quarters_difference--;
      $datediff = $quarters_difference;
      break;
    case "m": // Number of full months
      $months_difference = floor($difference / 2678400);
      while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
        $months_difference++;
      }
      $months_difference--;
      $datediff = $months_difference;
      break;
    case 'y': // Difference between day numbers
      $datediff = date("z", $dateto) - date("z", $datefrom);
      break;
    case "d": // Number of full days
      $datediff = floor($difference / 86400);
      break;
    case "w": // Number of full weekdays
      $days_difference = floor($difference / 86400);
      $weeks_difference = floor($days_difference / 7); // Complete weeks
      $first_day = date("w", $datefrom);
      $days_remainder = floor($days_difference % 7);
      $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
      if ($odd_days > 7) { // Sunday
        $days_remainder--;
      }
      if ($odd_days > 6) { // Saturday
        $days_remainder--;
      }
      $datediff = ($weeks_difference * 5) + $days_remainder;
      break;
    case "ww": // Number of full weeks
      $datediff = floor($difference / 604800);
      break;
    case "h": // Number of full hours
      $datediff = floor($difference / 3600);
      break;
    case "n": // Number of full minutes
      $datediff = floor($difference / 60);
      break;
    default: // Number of full seconds (default)
      $datediff = $difference;
      break;
  }   
  return $datediff;
}

Usage:

1
echo datediff('w', '9 July 2003', '4 March 2004', false)
  • Share/Bookmark

Zend Framework 1.8 Released!

Category : PHP

I just received Zend’s newsletter regarding the release of Zend Framework 1.8.

New features are
- rapid application development (RAD) using the new code generation classes, allowing developers to bootstrap their applications quickly
– also available are new cloud classes – abstracting and simplifying access to Amazon‘s S3 and EC2 services, exposing users to scalable deployment infrastructure.

 

Download Zend Framework 1.8

  • Share/Bookmark

50 Blogging Tools to Help you

Category : Information, PHP

 

blogging-tools

Blogging is more than just posting your views and any serious blogger would agree to that note hands down. There are many specialized tools available on the Internet that can enhance your website to a whopping extent and the only way to know what is going to work to your profits’ is to just try them out! Here is a list of 50 useful blogging tools (other than brains, creativity and the will to work!) that will help you in picking up your bet.

Let’s kick off with ‘Hosting, DNS and domainname’- that’s the first step anyways!

1. Domainscour: This is a website which helps you to find all the available domains in your niche within a span of few seconds. Powered by web 2.0.

2. MyIPneighbours: Snooping is always fun, right? This IP search facilitates in finding out how many other websites your ’shared host’ is hosting! This information if handled appropriately can be useful in web analytics and SEO.

3. WhoIshostingthis: A simple tool that enables you to find out the hosting company behind any website! Looking for a change in website hosting?

4. You Get Signal: This is a collection of various network tools and has in store, some of the best tools in the internet community. A treasure of useful resources!

Now for the attires, make-up and presentation – Design and Color.

5. GenFavIcon: An online tool that lets you select or create your own Favicons – Unique little icons that are displayed alongside a site’s name in the address bars of browsers.

6. Color Palette generator: You want similar colors (if not the same) like the ones in that particular image? Well, just type the URL of that image and you are gifted with a color palette, matching it. Simply wow! Isn’t it?

7. Color Scheme Generator 2: The tool basically generates a wide range of color schemes using the best optical impression (one of the authentic algorithms used in doing so!).

8. Font Tester: The right tool to find out the right style/font/size/color for your website has arrived! It’s a free online font comparison tool that does almost everything in the world of fonts.

9. Screen Size Tester: Unless you want your website to look distorted in different available browsers, you better check out this tool – it will definitely make your job a lot easier!

Now the geeky part (not exactly!) – Programming and coding

10. Grid: The fundamental of layouts is grids. ‘Grid’ is a manipulative and intuitive tool that facilitates the overlaying of a layout for any grid-based website.

11. CSS Superdouche: A superb tool that sensibly reduces the complex and unwanted parts of your CSS code to trimmed ones. You can call it the ‘designer of code’!

12. Centricle: You’ve done the finest coding possible for your website! Great! But one simple question – Is your CSS file compatible with all the browsers? Get your answers with this tool.

Web forms and its guild!

13. WuFoo: It’s an innovative HTML form builder that aids you in creating some of the most beautiful forms, invitations and surveys.

14. Web Form Factory: Standing true to its name, Web form factory is an open source generator of web forms. It automatically generates the much needed backend code to hold a particular form to a database.

15. PHP form: Stop drowning your heads into ‘Dummies for PHP’ and related books! It just takes three simple steps with this tool, to create a PHP form!

Content! One of the fundamentals of your website!

16. Orangoo spell check: It’s an online spell checker, a kind of free proof-reader! The results are very accurate and you don’t even need to download any kind of software or toolbar.

17. TheCompleteWord: Creative minds do need rest or maybe some new sources? Scourge through millions of articles here by just typing the necessary keywords!

18. WorldLingo: Just the way you don’t understand the language of people at the other end of the planet, similarly they don’t understand yours! Find the perfect translation of your language in English through this tool.

Social Bookmarking- A necessity.

19. AddThis: This tool spreads your website links throughout the internet at virus-like speed (although it’s not considered spam!) and makes it easier for people to bookmark your ‘darling’ and share it with others.

20. Social Marker: The promotion of your website is bound to take a huge leap with this tool in your kitty. This website offers free service through promotion and social bookmarking of your website. It saves a lot of your time and money for the PR!

Logos and more

21. Logo generator: It has a self-explanatory name! Generates lovely Web 2.0 logos for your website.

22. Buttonator: This tool gives the liberty of creating, dragging and dropping buttons to your website (web 2.0 compatible).

23. MyCoolButton: Creates marvelous web 2.0 buttons! It’s renowned for its user-friendliness and a host of options to help.

24. StripeDesigner: Create stripes – the easy way. These little things do add on to the Web 2.0 look.

25. Spiffy corners: Create rounded corners with the HTML and CSS provided by the tool, without the usage of some heavy images and JavaScript (this one’s heavy on brains, not size!).

26. Tartan Maker: If you aren’t the ’stripes’ types, then create and use ‘tartans’ for your background. Try this tool!

Up-time, SEO and marketing

27. URL trends: UrlTrends is a service that helps you track your marketing, perform competitive intelligence and get the data you need to make better domain purchases.

28. Word-tracker: “You enter a keyword and you get back hundreds of related keywords and an approximate of their daily search volume”- This isn’t fiction, it’s the functioning of this tool!

29. Crawl test: The search engine crawling issues of your website will be taken to task from now on. This tool happens to be a crawling issue diagnose specialist.

30. SiteUptime: A monitoring service for your website that notifies you via SMS or email in cases of your website is unavailable.

31. HostTracker: Register to this service and it’ll set some monitoring points, which will be monitored carefully in case of errors and other problems in your website.

32. OnlineMetatag: Good Meta tags will help you in fetching a good rank in a search engine. This tool generates different Meta tags for various search engines.

Rankings! Its time for your grades!

33. Blog Juice: Blog Juice Calculator Determine the “blog juice” for your blog using this tool from Text-Link-Ads and compare with various other blogs from the blogosphere. Juice is determined from your Bloglines subscription, Alexa rank, Technorati rank and inbound links in Technorati.

34. DNScoop: How much is your domain name worth? Use dnScoop to check and verify before you buy or sell, then discuss buy and sell domain names in the dnscoop forums.

35. Xinu: Check PageRank, Backlinks, Indexed Pages, Rankings and more.

36. Website grader: A free SEO tool from HubSpot that provides an Internet Marketing Report for your website. Tips on how to improve your existing website are also suggested by this tool.

37. Page Strength: Like its name, the tool weighs a site’s or more commonly the page’s visibility and relative importance.

38. PR checker: By adding our Page Rank Checker tool (page rank icon) to your site you can instantly and easily check the rank (check PR) of all your web site pages right on your web site.

39. Test Everything: CSS validators, HTML validators, web proxies, SEO tools, image tools and more – just check everything about your website here!

40. Popuri.us: It’s an indicator of the ‘popularity quotient’ of a link. A link’s popularity is checked on the basis of its ranking, social bookmarking, blogs and other factors.

Stats and Feedback

41. Google analytics: A gem of an analytical tool from Google. Forget the mundane information, it even prompts you on where your visitors come from and their interaction in the website too.

42. WebAGogo: A free online tool to test the quality of a website in tandem to its own set of established/relative parameters.

43. Piwik: It’s an ‘open-source’ web analytics software revealing some juicy and interesting information/reports of your website.

44. PHPmyvisites: An open source software for audience measurements, tracking of visitors and web statistics. One of the powerful and accurate in vogue!

Random ones

45. TagCloud generator: It generates web 2.0 tag clouds corresponding to the keywords on your website.

46. GickR: The online tool lets you create GIF animations. It’s free and instant.

47. Searchamabob: This tool facilitates your website visitors to search using Google or any other search engine that’s added along to this cool widget.

48. XML sitemaps: Placing this tool will help search engine crawlers to get to your website and track the changes in your pages more easily.

49. ShrinkTheWeb: It’s a website thumbnail provider, in fact the most powerful one.

50. Website ribbon: Create a unique ribbon for your website and lets you add it to your website instantly. It builds on the ‘brand’ image of your website and makes it look cooler than ever!

 

Reblog this post [with Zemanta]
  • Share/Bookmark

Google Reader POC Version 1.0

1

Category : General, Information, PHP, Product Releases

I was just wondering how google has progressed from its search engine to creating new icons for IT world. One of them was the google reader, i found this very interesting how the google reader caters to everybody needs. I am working on doctors & surgeons social networking site, there the client came up with an idea to implement google reader in the project to show users about the updates that they have in their baskets. I was chosen to create a POC(Proof of Concepts) for that. I took that as a challenge and created one very basic version of it. Here i would like to share with you the POC and the code.

Google Reader Copy
google-reader

Google Reader Copy

Please do comment so that i can make it better.

Download the code here.

Reblog this post [with Zemanta]
  • Share/Bookmark

Amit Yadav is Digg proof thanks to caching by WP Super Cache