7 Oct 2011

Hello, Evercode!

Good news, everyone!

Относительно недавно усилиями меня и еще нескольких людей на свет появилась компания Evercode Lab, которая должна стать моим главным проектом и детищем на ближайшее обозримое будущее. У нас, конечно, грандиозные планы и много идей.

У компании Evercode Lab естественно сразу появился свой блог, в котором мы планируем рассказывать о нас, о разных проблемах и их решениях (как технических, так и, возможно, не очень), и просто делиться своими мыслями в сферах разработки, бизнеса и других сфер, касающихся нашей работы. В связи с этим, скорее всего, в этом блоге оригинальные посты на технические темы будут появляться еще реже. Возможно, я буду публиковать сюда анонсы постов блога Evercode Lab. Еще вероятно, что мне взбредет в голову делиться в этом блоге какой-либо другой информацией. Who knows, посмотрим.

В любом случае, чтобы ничего не пропустить, рекоммендую подписаться и следить за блогом Evercode Lab, а также зафолловить твиттер компании.

На данный момент, уже можно почитать немного о компании, ознакомиться с разными workflow для git и посмотреть небольшой и простой совет по импорту локальных git-репозиториев на bitbucket.

Спасибо.

4c372867edef

 

12 Sep 2011

"LIKE" queries in app engine

It's been a while since my last post. Summer passed very quickly in work and some other new activities. I returned to studing and entered Master of Technology Enterpreneurship program in the university here in St.Petersburg. But I haven't stopped coding. And actually got some not very big pieces information which I want to share in several posts. There is nothing very new in all of them. It's just problems I met working on some projects. And solutions I found over internet which I want to keep here just in case.

In today's post I want to show little tricks that can do "LIKE" queries on App Engine Datastore. Latest is not actually designed to let this kind of queries, but there are some workarounds.

Appengine Datastore is based on google's own engine BigTable. It is actually a distributed storage system for structured data and it works brilliant in perspective of scalability, speed and amount of data it can work with. But nothing is perfect and it because of that benefits it lacks some functionality. Like the one in the title of this post.

Sometimes you need to implement search or some functionality to work wtih autocomplete in your apps and you certainly need a workaround for this. And luckily there are already some on the internet.

First thing I've found is to use inequalities. You can use them with string properties in the datastore. If you need query like following:

SELECT * FROM tablename WHERE field LIKE 'smth%'

you can use this instead:

SELECT * FROM tablename WHERE field >= ‘smth’ AND < :1″, u’smth’ + u’\ufffd’

In the parameter to this request the unicode character and ‘\ufffd’ code specify that the result must include the first characters appeared in greater-than inequality. It is formatted as unicode in order to concatenate correctly. You'll be able to read more detailed description if you check the links I'll attach at the end of the post.

As you can see you can only filter with the beginning of the word in this case. It's the best you can get in this case.

Second option give you the ability to filter through hole words and phrases. And it is to filter out content using python. It is reliable and seems better way to acomplish the task in our environment. But you should remember here always to controll the amount of data which you are searching against to keep your app fast and efficient. Python comes with a vast array of string comparing tools and again you can walk through examples in the first link at the end of the post.

So, that's it. As said earlier nothing very new and special, but hope it'll help you find usefull workarounds faster.

Here are the links to more complete descriptions, examples and answers:

20 May 2011

ZCE PHP 5.3 Study guide

Hi, everyone!

Today I want to shortly share with you some information on preparation for PHP certification. As I finally received my ZCE PHP 5.3 certificate about a week or two ago, I have no excuses putting it away any longer.


Img_0183

Previous time I prepared for the certification very thoroughly, studied different sources of information and also bought preparation tests on Zend site. I described process and sources in series of posts (only in Russian). This time I did not bother that much and was not so nervous or worried. So what I did was few steps which follows.

First, I made series of posts about new PHP 5.3 features. They are: namespaces, anonymous functions and late static binding. This was my first step to clear out for myself how they are working, what are useful for and also for starting using these features in projects I worked on.

Then I took the short study guide, which I compiled during preparation to previous certification, made some improvements, deleted unnecessary, added information on new questions according to test topics. And finally I read through it couple of times. Actually this time my preparations was finished and it appeared to be quite good to pass the exam.

So... here I want to share with you the updated ZCE PHP 5.3 short tutorial. Feel free to contact me if you find any mistakes or think something in it could and should be improved. May be (if I feel it becoming urgent) I'll put these materials somewhere as a site or github repository for example. Please, ping me if you think it should be done this way.

Click here to download:
ZCEPHP5.3tutorial.pdf (929 KB)
(download)

And finally one great bonus for all those people who are still preparing for certification or just want to improve their knowledge. Lorna Jane collected "ZCE 5.3 Study Links" and put them all together, so enjoy (I wish collection was already in place when I was preparing ;).

Good luck!

18 May 2011

ZFConf 2011

Организация

ZFConf - конференция посвященная разработке на Zend Framework и связанных с ним инструментах. В Питере проводится уже второй раз. В 2010 году конференция проводилась то ли в марте, то ли в апреле, в этом году срок немного сдвинули, назначив на 15 мая.

Самую подробную информацию по подготовке и организации события можно послушать в четвертом выпуске второго сезона подкаста zftalk.dev, где ведущий Виктор Фараздаги пригласил для беседы Павла Смольникова, директора компании Wizardtech, явлющейся главным зачинщиком мероприятия. Здесь только отмечу некоторые моменты по результатам и по сравнению с прошлым годом.

Прошлогодняя проблема с очередью в гардероб в этом году стала неактуальной, в этом плане время проведения было выбрано удачно.

При этом народу в этот раз было заметно меньше. Возможно, свою роль сыграло введение небольшой платы за посещение конференции. Хоть и не очень большой, но тем не менее, возможно, отбившей желание прийти у некоторых в принципе заинтересованных людей (по крайней мере я таких знаю).

Что еще немного смутило: финальный список докладов и окончательная регистрация появились на сайте zfconf.ru не сильно задолго до 15 мая. Точных дат не помню, но осталось такое ощущение. Кстати, расписание того, какой доклад в какое время будет проходить на сайте так и не появилось.

В раздаточном материале было общее расписание, тезисная информация по каждом докладу, ручка и бэджик. Последний, вроде, должен был быть пропуском на конференцию после обеда, но при этом он у меня валялся в рюкзаке и никто его у меня не спросил. Что не хватает в раздаточных материалах — это указания на профайлы докладчиков: твиттер, блог, гитхаб и прочее. По-моему, было бы не лишним.

И последний минус — отсутствие wi-fi и твиттер-трансляции по хэштегу. По-моему, на таких мероприятиях, это добавляет движняка.

Из плюсов: расписания придерживались очень четко, все докладчики успевали и рассказать по теме и ответить на вопросы. К 9, конечно, смысла ехать не было, я добрался до места в начале 11-го и ничего не пропустил. Кофебрейки в общем порадовали пирожками и бутербродами, но растворимый кофе Нескафе в пакетиках... :)

Может, я не заметил, но в этом году у конференции не было спонсоров. Что в общем-то очень зря, учитывая то, как сложно сейчас найти квалифицированных разработчиков и то, как они (разработчики), собравшись в одном месте поумничать друг перед другом, могли бы обратить свое внимание на замечательные условия работы в вашей компании.

И еще, непонятна ситуация с материалами с конференции: видео и слайдами докладов. Если я правильно понял, то первое будет доступно только тем, кто и так уже посмотрел все в живую. Что, по-моему, как минимум странно.

Доклады

В этом году в списке докладчиков было больше широкоизвестных в области веб-разработки компаний: Magento, KnpLabs, JetBrains, Sphinx, Geometria и др. Рассказывали, кстати, в основном не о самом ZF, а инструментах и практиках, методиках вокруг него. Что в общем-то и хорошо: на основной функционал есть мануал.

С докладчиками без проблем можно было пообщаться, позадавать свои «умные» вопросы и обсудить, что в голову взбредет. Те с радостью отвечали. В этом плане тусовка, мне кажется, удалась. Кто хотел с кем-то пообщаться, имел реальную возможность. Без тупняков, правда, тоже не обошлось :)

Пройдусь по заинтересовавшим меня докладам. Полный список c тезисами есть на сайте конференции.

Михаил Шамин из Geometria рассказал про создание своего «велосипеда» для удобной работы с базой. Мы увидели DDD, Data Mapper, описания через аннотации классов, рефлексию и грамотное разруливание связей. И без обложки книжки Фаулера не обошлось :) Схема в принципе классическая, но понравилось, как были решены нюансы, теперь думаю, как внедрить их в очень похожее решение, которое используем на работе.

Константин Кудряшов (@everzet) из KnpLabs рассказал про Behaviour Driven Development и Behat. Если вы про такое не слышали, то очень рекомендую сходить и почитать. Доклад помог лучше уяснить, что же это за зверь, зачем нужен и как может улучшить жизнь и программистам и их заказчикам. Плюс к этому, на мой взгляд, у Константина были самые нескучные слайды на презентации. В одном из кофебрейков удалось с ним еще пообщаться о KnpLabs, тренингах, Silex, Symfony и взаимоотношениях между заказчиками, менеджерами и разработчиками.

Рассказ Александра Гогельфа из Magento был посвящен сравнению Zend Server Job Queue и Gearman. Оба относятся к инструментам, позволяющим обрабатывать фоновые задачи. Очень актуальная вещь, если вы хотите ускорить работу ваших приложений в той части, где ответы возвращаются пользователям.

Николай Матвеев из JetBrains своим докладом напомнил мне в очередной раз, что надо уже наконец заставить себя перейти на использование PHPStorm. Говорилось в основном про удобство набора кода и навигации по нему, плюс про рефакторинг. Дебаг и интеграции с СКВ и багтрекерами не упоминались.

У докладчика о Sphinx, Владимира Федоркова, было замечено больше всех эмоций среди выступающих :) Получили полный обзор возможностей и вкусностей этого поискового движка, который действительно может сделать вашу жизнь намного лучше, причем бесплатно.

Разработчик из перспективного стартапа ДзенМани, Дмитрий Чижевский, рассказал про то, как он делал REST API для их проекта. Хоть ничего принципиально нового я и не узнал, но эта тема мне очень интересна, так как с проектированием и разработкой API приходится сталкиваться регулярно. Поэтому после докладов несколько связанных вопросов мы с ним еще обсудили.

Завершили конференцию темой, без которой нельзя было обойтись. Про Dependency Injetction очень внятно и понятно рассказал Алексей Качаев. Тема была раскрыта действительно качественно. Надеюсь, слайды этого доклада можно будет найти где-нибудь в сети.


Спасибо организаторам и докладчикам. Было интересно!

19 Apr 2011

Using Tor with PHP

Tor is a system intended to enable online anonymity, composed of client software and a network of servers which can hide information about users' locations and other factors which might identify them. Use of this system makes it more difficult to trace internet traffic to the user, including visits to Web sites, online posts, instant messages, and other communication forms. It is intended to protect users' personal freedom, privacy, and ability to conduct confidential business, by keeping their internet activities from being monitored.

(extract from wikipedia article)

Today I want to share some knowledge about how one can work with Tor using PHP.

Use cases

There are several reasons why you might need Tor. For example, you really want your network interaction be anonymous and don't want your requests being able to traced. One more common reason that I often meet is necessity to overcome some limits (that was exactly my case... several times). For example, if some service exposing usefull API have limit on requests from one IP-address. Or some site which you have a task to grab some info from do not actually like to be roboted or have some limits which contradicts with your deadlines (or stupidoverrated client's requirements). You should understand that those limitations is a will of site or service owners, so it is not very polite to hack them this way. But sometimes you just don't have any alternatives.

Installaion

I won't describe here the hole process of software installation. It is not necessary as full and good documentation is available on Tor Project site. I just want to point out few things. First, you need not only Tor to be installed but also some proxy-server (Polipo, for example). Second, you should distinct ports of your proxy, of your tor socks and controll port one from another. If you go through hole installation process – you'll understand. If you need full stack fast just to test it on your local machine, you can just download bundle.

Using

Ok, let's see, how you can actually use tor. It is very easy and straightforward. To make request through tor using curl you just need to add CURLOPT_PROXY option. Look at the example:

 

$_torProxyPort is actually access port of your proxy installation (default polipo port in this case).

But that's not all. You'll probably will need to switch identities automatically on some conditions in your code. That's why here is very simple example how you can do it:

You'll need to extended example to match you configured tor authentication method. May be you'll want to make methods for some other tor features, but I think it's very rare case.

Here are some links where I've found information:

That's it. Use this information and instruments properly not to be a bad ass which just don't want to be banned ;)

Roman's Posterous

I know I was born.
And I know that I'll die.
I am mine.

Co-founder at Evercode Lab
Co-founder at Comicsbay