Для получения полного доступа
зарегистрируйтесь.

Section:
Sub-section::
Languages:


samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

PHP has excellenet intl extension which is based on ICU library for algorithms and CLDR data for locale data. The code shows how to get currency symbol by currency code using intl.

Example usage:

echo getCurrencySymbol('EUR');
echo getCurrencySymbol('GBP');

would output and £.

By specifying locale code as a second argument you can get currency representation that is common for that locale:

echo getCurrencySymbol('RUR', 'ru_RU');

would output р..

function getCurrencySymbol($currencyCode, $locale = 'en_US')
{
    $formatter = new \NumberFormatter($locale . '@currency=' . $currencyCode, \NumberFormatter::CURRENCY);
    return $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
}

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

The query is an efficient way to get 10 latest comments limiting it to maximum one comment per post.

SELECT *
FROM comment c1
LEFT JOIN comment c2 ON c1.id < c2.id AND c1.post_id = c2.post_id
WHERE c2.id IS NULL
ORDER BY c1.id DESC
LIMIT 10
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

While it's kinda pointless, it's possible to use callbacks as URL handlers totally avoiding MVC in the same style as many micro-frameworks do.

require 'vendor/autoload.php';
require 'vendor/yiisoft/yii2/Yii.php';


$app = new CallbackWebApplication([
    'id' => 'MyApplication',
    'basePath' => __DIR__,
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],
    ],
]);

$app->onGet('hello/<name>', function($name) {
    return 'Hello, ' . $name . '!';
});
$app->run();
<?php
class CallbackWebApplication extends \yii\web\Application
{
    private $callbacks = [];

    /**
     * @inheritdoc
     */
    public function handleRequest($request)
    {
        list ($route, $params) = $request->resolve();
        if (preg_match('~callbacks/(\d+)~', $route, $matches) && isset($this->callbacks[$matches[1]])) {
            $result = call_user_func_array($this->callbacks[$matches[1]], $params);
        } else {
            throw new \yii\web\NotFoundHttpException();
        }

        $response = $this->getResponse();
        $response->data = $result;
        return $response;
    }

    public function onGet($pattern, callable $callback)
    {
        // it's possible to implement our own UrlRule class to handle it
        // but I was too lazy
        $callbackIndex = count($this->callbacks);
        $this->callbacks[$callbackIndex] = $callback;
        Yii::$app->getUrlManager()->addRules([
            $pattern => 'callbacks/' . $callbackIndex
        ]);
    }
}
Gravatar image
creocoder
  • Reputation: 3
  • Snippets: 1
  • Revisions: 0
    var loader = function () {
        var url = $('meta[name="api-base-url"]').attr('content') + 'projects';
        var xhr;

        return function (args) {
            args = $.extend({ refresh: false }, args);

            if (args.refresh) {
                url = $('meta[name="api-base-url"]').attr('content') + 'projects';
            }

            if (url && (!xhr || xhr.readyState === 4)) {
                xhr = $.get(url, function (data) {
                    if (args.refresh) {
                        $projects.find('tbody').html(projectsTemplate(data));
                    } else {
                        url = (((data || {})._links || {}).next || {}).href;
                        $projects.find('tbody').append(projectsTemplate(data));
                    }
                });
            }
        };
    }();

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

The approach demonstrated is used in my Sitemap package to allow generating huge sitemaps consisting of hundreds thousangs of locations.

// we'll buffer data in memory in order not to write too often
$bufferSize = 1000;

$filePath = 'test.xml';

$writer = new XMLWriter();
// using memory for buffering
$writer->openMemory();


$writer->startDocument('1.0', 'UTF-8');
$writer->setIndent(true);
$writer->startElement('test');

while ($i < 10000) {                  
	if ($i % $bufferSize) {
		// if buffer is full, flush its contents into the file
		file_put_contents($filePath, $writer->flush(true), FILE_APPEND);
	}
	$writer->writeElement('item', $i);
}

$this->writer->endElement();

$this->writer->endDocument();

// write the rest of the buffer
file_put_contents($filePath, $writer->flush(true), FILE_APPEND);
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Thanks to closures we can avoid using global flag which spoils the scope.

The code could be executed in any browser console. To trigger it, click anywhere on the page.

window.addEventListener('click', function () {
    var i = 0;
    return function () {
        window.alert('You\'ve clicked it ' + (++i) + ' time(s).');
    };
}());
Snippet,  PHP

Types and in_array

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5
$array = array('one', 'two');
var_dump(in_array(0, $array)); // true
var_dump(in_array(0, $array, $strict = true)); // false
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Named scopes are quite useful and are familiar to developers who work with Yii. The code shows how to get these in CodeIgniter.

class Post extends Model
{
    function __construct() {
        parent::__construct();
        $this->db->from('post')->order_by("created_at", "desc");
    }
 
    function limit($number) {
        $this->db->limit($number);
        return $this;
    }
 
    function all() {
        return $this->db->get()->result();        
    }
}

$posts = $this->post->limit(10)->find();
foreach($posts as $post) {
	// ..
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5
SELECT *
FROM news
WHERE id IN (2, 10, 3, 88, 23)
ORDER BY FIELD (id, 2, 10, 3, 88, 23)
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Safari and old Chrome are triggering additional popstate event on page load. Modern Chrome fixed it but it still happens in current Safari.

The idea is to register a handler after initial popstate pops. It is triggered on load so we're adding handler for it. setTimeout with 0 delay is to make sure handler registered last.

$(window).load(function() {
    setTimeout(function() {
        $(window).on('popstate', function (e) {
                // handle it
        });
    }, 0);
});