Programming languages Archives - Page 2 of 2 - developed.be

What’s a pivot table?

A pivot table is a database table that only exists to serve a many-to-many relationship. Say you have a table “customer” and a table “drinks”. If you want to know which customer ordered which drink you have to create a pivot table customer_drinks(customer_id, drink_id).

Laravel can handle these tables (semi)automatically.

Define the pivot table in Laravel

If you want to define the pivot table in Laravel, you have to create a belongsToMany relationship. Example:

Continue reading “Laravel 4: pivot table example (attach and detach)”…

  • Published:August 21st, 2013
  • Category:Lavarel, php
  • 2 comments

Laravel supports the PHP Framework Interop Group naming conventions. You can find them on the PHP-FIG website.

In short:

  • Generally database columns are snake_case but property names are camelCase. Eloquent is able to do the conversion automatically.
  • Class names must be declared in StudlyCaps.
  • Class constants must be declared in all upper case with underscore separators.
  • Method names must be declared in camelCase. (this used to be snake_case in L3)
  • Property names and function arguments have generally not a specific rule, but must be written according to the package. The Laravel doc about the convention doesn’t give more information about property names.. The only rule is: always use the same. I would suggest camelCase.
  • Function names are camelCase. (however the Official PHP coding standards advices snake_case).
  • For Variables names I would suggest camelCase, however snake_case is advised by the Official PHP coding standards, in contrast with the recommandations from the Zend Framework, which explicitly forbids underscores. Variables are not mentioned in the PHP Framework Interop Group and I can’t find any examples in the base Laravel framework because all variable names are single words.

I’d like to add that naming conventions are a controversial subject, because a lot of standard PHP functions don’t follow any naming convention.

While jQuery is a great improvement on classic Javascript, it’s still not perfect. What works in version 1.3 doesn’t automatically work in 1.7 and what works in Firefox, doesn’t automatically work in IEx. The syntax isn’t very straightforward and some properties are misleading (eg: .val() vs .value())

This is an updated! incomplete list of stuff I need regularly that works in jQuery/javascript:

DOM Hierarchy

Get an ancestor

$("#element").parents(".these_ancestors")

Continue reading “The jQuery and Javascript code snippets you should learn by heart”…

I’m getting back at the PHP Laravel framework. I studied most of its documentation and have a decent idea what it can do.

However, I’ve reached at a point where I need a decent “imagecache” functionality, like you have in Drupal. There’s an attempt in Laravel but it doesn’t come close to the easiness of imagecache (probably one of the best Drupal modules).

Further down the road I must have some permission-system, user forms, a comment tool system, Mollom protection, Captcha’s, forgotten-password-mails, newsletter forms, node locking, search integration, OpenGraph, social media toolbars, permalinks and a zillion other features.

The thing is: do I have to reinvent the wheel? Do I even want to do that?

How much time does it take to make a light version of imagecache? If it’s done in half a day it might be worth it. The powerful thing is that I have total control about every little detail. Gone are the days that you can’t get around something because that’s the way it goes in Drupal (eg: must every node-type have a body-field?)

Can I make an opensource CRM/CMS based on Laravel? Ready for others? Is anybody waiting for that?

(for those wondering if I’m wasting someone else’s money, I spend most of my research in my spare time)

Update: I decided to go for it. Things go pretty well so far but, like any IT-project, it’s a lot of work.

To be honest, I’m a bit fed up with Drupal lately. We’re stuck with an ever-growing fat Drupal6 site, and the monster doesn’t get easier to maintain. The question isn’t if we will upgrade, but to what we will upgrade. The logical upgrade to Drupal7 will be enormous because our website has over 150.000 lines of custom php-code (not mentioning css, js, themes). So moving to Drupal 7 or creating something entirely new based on a framework… I don’t dare to say how much difference in time it will make, but I do know that the new thing must be a giant step forward to what we have now.

Why moving from Drupal to a Framework?

As much as I love Drupal, the thing is… a lot of modules do kind of what I want, but they don’t do exactly what I want. Customizing a contributed module sometimes takes me as long as I would write it myself. Especially when there’s little info in the README-file or when there are hardly any comments in the code. To give you an exampe: it’s faster to lookup the url for the admin-page in the menu-hook, than to find it in the documentation or in the navigation.

Plus, what irritates me the most. When you have +75 modules, +100.000 nodes and +10 currently logged in users, the thing gets slow.. slooowww! Even with advanced caching tools such as Memcached,  view-cache or Varnish, the thing still goes slow, even on a dedicated server. No wonder: every hook is checked for each and every request.

So I’m looking for something faster and more OO-like. I have a C#-background and the way classes are mimicked in php (including inheritance, namespaces) is simply terrible. I’d dare to say Drupal goodbye, as long as Drupal 8 isn’t released an is more decent.

My comparison of PHP Frameworks

Pfhew, long introduction, but here’s my research on PHP-Frameworks. Briefly, a framework provides a set of functions and classes to help developers write code faster and more structured. Most of them implement certain design patters, of which MVC is by far the most popular. The aim of MVC is to seperate the database-talking-code (Model) from application-specific code (Controller) from html (View). It also features a URL-mapping system to set “clean url”-rules and to separate the code-files from the actual urls (eg: /bootstrap.php shouldn’t be accessible through a browser).

Some devs use the bootstrap of a CMS as a framework-starter (like my RSS-boostrap), but it should actually be the other way around: a CMS should be build on a framework. Drupal8 will (maybe) rely on parts of Symfony2, but that won’t be out till 2014.

Continue reading “PHP Frameworks, which to choose in 2013? A comparison.”…

I upgraded my Ubuntu 10.04 to Linux Mint 14. After installing LAMP I got a Drupal WSOD on a previously well working site. As it turned out most errors came from deprecated php-functions and deprecated call by references to functions, introduced with the release of PHP 5.4.

At first I was a somewhat encouraged to solve those deprecated functions, but I gave up pretty soon. Drupal 6 isn’t designed for 5.4. Tweaking Drupal feels the same as upgrading to Drupal 7. Therefor, I keep it to PHP 5.3.

To downgrade 5.4 to 5.3 I recommend this script on the Ubuntu forums.

When installing the combo php5-fpm together with Nginx or Apache, you might run into this error:

[error] 4942#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: example.com, request: “GET /phpinfo.php HTTP/1.1”, upstream: “fastcgi://127.0.0.1:9000”, host: “example.com:80”

This is actually not an nginx error but a php-error. Nginx tries to contact php5-fpm, but fails in doing so. This is because it’s probably not running, or because the configuration is wrong.

Check if it’s running

To troubleshoot this, test if fpm listens on 9000. You can do this with telnet.

telnet 127.0.0.1 9000

Alternatively:

sudo netstat -tlpn | grep :9000

Telnet should return “Connected to 127.0.0.1”

Netstat should return a line starting with “tcp” and ending with “LISTEN”

Troubleshoot

If it doesn’t return anything or if it returns an error, it’s because fpm is not listening on port 9000. To solve this:

sudo gedit /etc/php5/fpm/pool.d edit

edit the line that says “listen = ” to:

listen = 9000

Then restart fpm:

sudo /etc/init.d/php5-fpm restart

You don’t even have to restart apache or nginx. It should work right away.

This function will print a large list of all the variables that are declared in the current scope:

<?php print_r(get_defined_vars()); ?>

An interesting variable is $node, but it is not always accessible.

Our main RSS-feed at DeWereldMorgen.be is the most requested page next to our homepage.

It seems logic, think of how many rss-readers hourly check the feed. And, think of how many cpu and RAM that consumes, certainly with a fat system like Drupal.

An RSS-feed is easy to make in PHP. All you need is one custom query and a decent library like the Universal Feed Generator to generate the XML.

Create stripped version of Drupal setup

I used the minimal code that is needed to work in the Drupal framework. So I made a blank php-file in my www-root with this code:

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

This code has the security and functions of Drupal, but without the menu’s, theme’s, and a lot of module hooks. You don’t need a menu or a theme to create an RSS-feed, do you?

So I created my RSS-feed with just this in my php-file:

  • the drupal_bootstrap function
  • the Universal Feed Generator library included
  • one query with db_query()

With cache

Let’s see performance wise. This is the report of a feed generated based on a user’s blog and articles. Memcache was not cleared before execution. Stats are generated with XHProf.

Normal setupMy stripped setup
Number of function calls115.20018.400
Consumed RAM126 MB62 MB
Total execution time1.169 MS462 MS
Number of database queries3315
Query execution time137 MS80 MS

Performance wise, my solution is twice as fast.

Without cache

These stats are generated when caches were cleared.

Normal setupMy stripped setup
Number of function calls3,284,34383,330
Consumed RAM172 MB76 MB
Total execution time9,131 MS1,000 MS
Number of database queries926131
Query execution time769 MS183 MS

9x as fast. 7x less queries.

Of course, this is just for the first run, but still.

More soon. Please discuss this idea.

  • Published:November 8th, 2012
  • Category:C#

As an alternative to arrays in C#, the MS-programmers use “generic collections”; some kind of an array where the value could be any kind of object. There are 3 big types of generic collections: lists, hashsets and dictionaries. This article is about when you use which type of generic collection, based on own experiences and literature.

List

A list is ideal for all kinds of collections with less than 5 elements.

A list is fast in adding elements, but exponentially slow in searching for elements. The more elements, the slower a search will be.

For searching elements, always use Find() (Find() is up to 3x as fast as First(), and First() is about 1,5x as fast as Single()).

Elements in a list maintain an order (= enumerable)

Dictionary

A dictionary has a key/value principle, like an array.

Searching for keys is faster than searching for values. Arrange your dictionary that the key value is what you search for. If you need to search for both (keys and values), it’s best to maintain two identical dictionaries, but in the second dictionary, the keys and values are switched.

The creation is slower than the creation of a List.

Every key must be unique.

Searching keys in a Dictionary is up to 3x as fast than searching in a Lists (if the List is bigger than 5 elements). The size of a dictionary doesn’t make the search significantly slower.

A Dictionary is slower to add an element to than a List.

Elements in a Dictionary maintain an order (= enumerable)

Use dictionaries for big lists where searching for elements is more important than adding elements.

To get a value from a key, TryGetValue() is the fastest.

Hashset

A hashset doesn’t maintain order (= not enumerable). This is different from a Dictionary and a List.

Use a hashset when you want to check if an element is in a list (with “Contains”).

Use a hashset when your list could contain thousands of elements.

Hashsets, like Dictionaries, use the GetHashCode() method of an object to check if it’s unique. If you constructed a hashset with your own objects, you have to make sure the object contains a GetHashCode() override (to check if it’s unique).

In short

List (< 5 elements)List (> 5 elements)DictionaryHashset
Adding elementsFastestFasterSlower
Searching elementsFastest(Very) slow (exp.)FastFaster
Enumerable
(maintains order, loop-able)
YesYesYesNo
Ideal size<5<51000x1000x
« Previous Page