Home
About
Search
🌐
English Română
  • Yahoo! Open Hack Europe 2011 at Bucharest!

    Citește postarea în română

    Apr 21, 2011 hack Yahoo
    Share on:

    Yahoo! Open Hack Europe 2011 will be held in Bucharest! Between 14-15 May we are the lucky Europeans to host this event.

    At this event there are two types of tickets: Tech Talk and Hacker. Those who choose Tech Talk will attend seminars and awarding only, while those who choose Hacker will stay overnight to work on the project they’ve chosen.

    Important figures from the Yahoo! staff will be present, so in short is an event that you must not miss!

  • Closures and lambda functions in PHP vs. JavaScript

    Citește postarea în română

    Apr 16, 2011 anonymous functions closures JavaScript lambda PHP php5.3
    Share on:

    JavaScript and PHP support both lambda functions and closures. But the terms are poorly understood in both programming languages ​​and are often confused with each other.

    Lambda functions

    Also called anonymous functions. They refer to functions that can be called without being bound to an identifier. One of their purposes is to be passed as arguments. The Lambda name was introduced by Alonzo Church, inventor of lambda calculus in 1936. In lambda calculus all functions are anonymous.

    JavaScript

    In JavaScript lambdas are part of the standard set and there are the preferred method of defining functions.

    For instance:

    1var add = function (a, b) {
    2     return a + b;
    3}
    4alert(add(1, 2)); // 3
    

    Lambda functions are used almost in any context when it comes to JavaScript, like:

    1window.onload = function (e) {
    2     alert('The page has loaded!');
    3}
    

    PHP

    In PHP, lambda functions were introduced in version 4.0.1 using create_function. In version 5.3+ a similar syntax to JavaScript was added, a much more readable and elegant way of defining a function.

    This means that in PHP there are two ways of creating a lambda function:

     1// PHP 4.0.1+
     2$add = create_function('$a, $b', 'return $a + $b;');
     3
     4// vs.
     5
     6// PHP 5.3+
     7$add = function ($a, $b) {
     8     return $a + $b;
     9};
    10
    11echo $a(1,2); // 3
    

    Lambda functions can be used as parameter for other functions, such as usort:

    1$array = array(4, 3, 5, 1, 2);
    2usort($array, function ($a, $b) {
    3     if ($a == $b) {
    4          return 0;
    5     }
    6     return ($a < $b) ? -1 : 1;
    7});
    

    Even more, PHP 5.3+ allows calling an object as a anonymous function:

    1class test {
    2     function __invoke($a) {
    3          echo $a;
    4     }
    5}
    6$a = new test();
    7$a('test'); // 'test'
    

    Closures

    The closure is really the misunderstood concept of the two. In general confusion appears because closures may involve lambda functions. A closure refers to the ability of a function/object to access the scope in which it was created even if the parent function has ended it’s execution and returned. In other words, the function/object returned by a closure is running in the scope in which it was defined.

    In JavaScript the notion of closure is part of the standard arsenal, because the language is not based on the traditional object model, but rather on prototypes and functions. But JavaScript has some traditional object model parts, like the fact that you can use “new” to construct an object based on a function that plays the role of a class. In PHP closures are more of an new way to approach problems, because PHP is part of the traditional object model family.

    JavaScript

    In JavaScript the notion of closure is widely used, it’s so popular because JavaScript is not a traditional object orientated language, but rather a functional one, based on prototype inheritance.

    JavaScript doesn’t have Public, Private and Protected, but rather only Public and Private and objects an inherit from each other, without using classes.

    Another issue is the scope, because the global scope is used by default. This issues can be fixed in an elegant fashion using closures:

     1var closure = function () {
     2     var sum = 0;
     3     return {
     4          add: function (nr) {
     5               sum += nr;
     6          },
     7          getSum: function () {
     8               return sum;
     9          }
    10     }
    11}();
    12
    13closure.add(1);
    14closure.add(2);
    15console.log(closure.getSum());
    

    In the example above, sum is a private property and in theory can only be accessed and modified by the closure function. The interesting part is that the parentheses from the end of the function definition, signify that this function will be immediately  executed and therefore will return the result which is an object. At this point the original function will only exist for serving the return object, encapsulating therefor the private variable.

    Although the function has finished execution, through this closure the returned object can still access the variables defined in the function scope, because that was the environment in which it was created.

    This becomes even more interesting when a function returns another function:

     1var counter = function () {
     2    var counter = 0;
     3    console.log('in closure');
     4    return function () {
     5        console.log('in the anonymous function');
     6        return ++counter;
     7    };
     8};
     9var counter1 = counter();
    10
    11console.log(counter1()); // 1
    12
    13var counter2 = counter();
    14console.log(counter2()); // 1
    15console.log(counter1()); // 2
    

    The output will be:

    1in closure
    2in the anonymous function
    31
    4in closure
    5in the anonymous function
    61
    7in the anonymous function
    82
    

    What actually happens is that the first function is executed and returns an anonymous function that can still access the environment in which it was created. In my opinion this is where the confusion between closures and lambda functions comes from, because a function returns another function.

    The difference between examples is that in the first one the closure function executes immediately, and in the second example when counter is executed it’s returning a result that is actually a function definition, which in turn can be executed. Of course the second example can be modified to act just like in the first example using parenthesis.

    PHP

    As I said above, the notion of closure in PHP is not as important as in JavaScript.

    Considering that lambda functions are available in the language since version 4, closures only appeared with PHP 5.3+.

    Because of the block scope nature of PHP, there is a better encapsulation but there is a lot less flexibility compared to JavaScript. Basically in PHP you must specify using the use instruction what will the anonymous function be able to access from the closure scope.

     1function closure () {
     2     $c = 0;
     3     return function ($a) use (&$c) {
     4          $c += $a;
     5          echo $a . ', ' . $c . PHP_EOL;
     6     };
     7}
     8
     9$closure = closure();
    10
    11$closure(1);
    12$closure(2);
    

    Unlike JavaScript, in PHP closures can not return objects, or rather the object can not be bound to the scope in which it was created, unless you send the variables as a reference to the constructor, in which case is not very elegant and I can’t imagine a scenario that would absolutely need closure for this.

    Like in the JavaScript examples, instead of parentheses “()” at the end of the function, in PHP to run a function immediately after defining it call_user_func() or call_user_func_array() can be used:

     1$closure = call_user_func(function () {
     2    $c = 0;
     3    return function ($a) use (&$c) {
     4        $c += $a;
     5        echo $a . ', ' . $c . PHP_EOL;
     6
     7    };
     8});
     9
    10$closure(1);
    11$closure(2);
    
  • The story of JavaScript told by Douglas Crockford la Yahoo!

    Citește postarea în română

    Apr 9, 2011 Douglas Crockford JavaScript
    Share on:

    Douglas Crockford on JavaScript

    As I am a big fan of Douglas Crockford, the inventor of JSON, several weeks back I’ve found a new series of presentations. The presentations took place in 2010 and can be found on the YUI blog dedicated page: http://yuiblog.com/crockford/.

    Why am I a Crockford fan? There were 3 thinks that surprised me on his first presentation I’ve seen:

    • he argued fiercely that JavaScript has good parts, but they are not understood,
    • said that JavaScript is a functional language, and as such should be taken in order to discover its beauty,
    • he was one of the few to write a true programming book for JavaScript and not just a collection of special effects like the majority did at the time.

    The series “Crockford on JavaScript” at Yahoo!, is not exactly new but very topical.

    What is different about this presentations is that there not completely focused on syntax, language and “good parts”, but rather on the overview picture, all the story of the language, including the storys of the languages that influenced it.

    The presentations are quite long, over an hour each, but very interesting in my opinion, especially if you’re a fan of computer history.

    Part Three can be a bit more difficult because there are some notions that may seem quite bizarre. But once you get familiar with them, many other things become more clear.

  • ssh key based authentication

    Citește postarea în română

    Apr 5, 2011 ssh
    Share on:

    The ssh key based authentication is useful when you don’t want to type the password each time. Also is useful when for instance sshfs is used and mounting takes place without entering a password.

    The end result should do login with the following command:

    1$ ssh work
    

    Server

    In Ubuntu the server installation is done with:

    1$ sudo apt-get install ssh
    

    For other distributions the packege is usually called ssh or OpenSSH.

    On server-side you must activate the public key authentication in the sshd_config file:

    1#/etc/ssh/sshd_config
    2
    3PubkeyAuthentication yes
    

    Client

    On client-side the public/private key pair must be generate:

    1$ ssh-keygen -t rsa -b 1024
    

    Where the type of the key is rsa and 1024 is the size. Bigger is safer.

    The public key must be copied on the server using the following command:

    1$ ssh-copy-id -i ~/.ssh/id_rsa user@192.168.1.1
    

    The -i option and key path are optional, if there was generated a single key on the client in ~/.ssh directory that one will be used as default.

    Right now it should work to login using the next command without prompting for password:

    1$ ssh user@192.168.1.1
    

    Alias

    The last step is creating an alias, in this case it will be called “work”.

    You must make a config file in the ~/.ssh directory. The file must have 600 rights, that is reading and writing only for owner.

    1$ cd ~/.ssh
    2$ touch config
    3$ chmod 600 ~/.ssh/config
    

    In this file aliases will be set:

    1Host work
    2HostName 192.168.1.1
    3User user
    4IdentityFile ~/.ssh/id_rsa
    

    At this step authentication to the previously defined host can be made with the command:

    1$ ssh work
    

    To learn more about ssh aliases checkout the manual:

    1$ man ssh_config
    
  • Parse ini files in PHP

    Citește postarea în română

    Mar 12, 2011 ini parse_ini_file PHP
    Share on:

    Why “ini” files? Because there are more convenient! Most servers in the *nix world have “ini” or “conf” configuration files. In the PHP world there are preferred PHP configuration files, which are usually arrays. Wouldn’t be more elegant to have an ini file without PHP code in it?

    Fortunately PHP has a couple of native functions just for that: parse_ini_file and parse_ini_string.

    The principle is very simple, you give an configuration ini file as a parameter and it will return an array.

    A little example:

     1;config.ini
     2
     3[simple]
     4number = 1
     5another = 2
     6fraction = 0.2
     7
     8[escape]
     9path = /usr/bin/php
    10url = https://blog.claudiupersoiu.ro
    11error = '<a href="%path%">%error%</a>'
    12
    13[array]
    141 = a
    152 = b
    163 = c
    

    To parse the previous file:

    1$config = parse_ini_file('config.ini', true);
    2var_dump($config);
    

    The second parameter specifies if the sections will become keys in the resulting array. Honestly I don’t think of a case when that wouldn’t be useful.

    Seems slow? In fact for the file above is faster to parse then to include an array already parsed. The difference on my computer is ~0.00002s.

    But the above file is not exactly big, so let’s get to a more serious ini file, like php.ini. Here the difference was bigger in favor of array, which won whit an advantage of ~0.0003, which means about half of parsing time that was ~0.0006s.

    Taking into consideration that my computer is pretty fast and concurrent request can add an overhead for big files, sometimes it is useful to use a cache of the ini file.

    Fortunately this is easy to do in PHP.

    1$cache = var_export($config, true);
    2
    3file_put_contents('cache/config.php', "<?php\n\$config = " . $cache . ';');
    

    Now you just need to include cache/config.php file and of course regenerate it when something changes in the ini file.

    PHP should have write permissions for the cache directory.

    • ««
    • «
    • 8
    • 9
    • 10
    • 11
    • 12
    • »
    • »»

Claudiu Perșoiu

Programming, technology and more
Read More

Recent Posts

  • 30 years of PHP
  • HTTPS certificate monitoring in Home Assistant
  • Adding a slider to Tasmota using BerryScript
  • The future proof project
  • Docker inside wsl2
  • Moving away from Wordpress
  • Custom path for Composer cache
  • Magento2 and the ugly truth

PHP 50 MISCELLANEOUS 47 JAVASCRIPT 14 MAGENTO 7 MYSQL 7 BROWSERS 6 DESIGN PATTERNS 5 HOME AUTOMATION 3 LINUX-UNIX 2 WEB STUFF 2 GO 1

PHP 36 JAVASCRIPT 15 PHP5.3 11 MAGENTO 7 PHP6 7 MYSQL 6 PHP5.4 6 ZCE 6 CERTIFICARE 5 CERTIFICATION 5 CLOSURES 4 DESIGN PATTERNS 4 HACK 4 ANDROID 3
All tags
3D1 ADOBE AIR2 ANDROID3 ANGULAR1 ANONYMOUS FUNCTIONS3 BERRYSCRIPT1 BOOK1 BROWSER2 CARTE1 CERTIFICARE5 CERTIFICATION5 CERTIFIED1 CERTIFIED DEVELOPER1 CHALLENGE1 CHM1 CLASS1 CLI2 CLOSURES4 CODE QUALITY1 CODEIGNITER3 COFFEESCRIPT1 COLLECTIONS1 COMPOSER1 CSS1 DEBUG1 DESIGN PATTERNS4 DEVELOPER1 DEVELOPMENT TIME1 DOCKER2 DOCKER-COMPOSE1 DOUGLAS CROCKFORD2 ELEPHPANT2 FACEBOOK2 FFI1 FINALLY1 FIREFOX3 GAMES1 GENERATOR1 GO1 GOOGLE1 GOOGLE CHROME1 GOOGLE MAPS1 HACK4 HOMEASSISTANT3 HTML2 HTML HELP WORKSHOP1 HTML51 HUG1 HUGO1 INFORMATION_SCHEMA1 INI1 INTERNET EXPLORER3 IPV41 IPV61 ITERATOR2 JAVASCRIPT15 JQUERY1 LAMBDA1 LINUX1 MAGENTO7 MAGENTO22 MAP1 MINESWEEPER1 MOTIVATION1 MYSQL6 NGINX1 NODE.JS2 NOSQL1 OBSERVER3 OBSERVER PATTERN1 OOP1 OPERA1 OPTIMIZATION1 ORACLE1 PAGESPEED1 PAIR1 PARSE_INI_FILE1 PHONEGAP2 PHP36 PHP ELEPHANT2 PHP FOR ANDROID1 PHP-GTK1 PHP42 PHP53 PHP5.311 PHP5.46 PHP5.53 PHP5.61 PHP67 PHP7.41 PROGRAMMING1 REVIEW1 ROMANIAN STEMMER2 SAFARY1 SCALAR TYPE HINTING1 SCHEME1 SET1 SHOPPING CART PRICE RULE1 SINGLETON1 SOAP1 SPL2 SQLITE1 SSH1 STACK TRACE1 STDERR1 STDIN1 STDOUT1 SUN1 SYMFONY2 TASMOTA1 TEST TO SPEECH1 TITANIUM2 TRAITS1 TTS1 UBUNTU1 UNICODE2 UTF-82 VECTOR1 WEBKIT1 WINBINDER1 WINDOWS2 WORDPRESS1 WSL21 YAHOO3 YAHOO MAPS1 YAHOO OPEN HACK1 YSLOW1 YUI1 ZCE6 ZCE5.31 ZEND3 ZEND FRAMEWORK3
[A~Z][0~9]

Copyright © 2008 - 2025 CLAUDIU PERȘOIU'S BLOG. All Rights Reserved