Настройка локальной среды для разработки на CodeIgniter в Mac OSX, используя MAMP

Настройка локальной среды для разработки на CodeIgniter в Mac OSX, используя MAMP Удобно иметь на локальной машине копию проекта и работать только с ней, а когда что-то готово для переноса на рабочий сайт, с лёгкостью опубликвать локальную версию. Покажем как настроить удобную связку CodeIgniter+MAMP

Внимание: начиная с версии 2.0.1 разработчики сами добавили в систему настройку сред. Желательно обратиться к документации и делать как они советуют. Эта статья актуальна для версий до 2.0.1.

Недавно в этой статье мы настраивали локальную и рабочую версии для проекта на фреймворке Yii. Там мы не заостряли внимание, но это тоже было настроено в MAMP, хотя вы легко настроите и в Denwer'е. Это не суть, все шаги похожи и для пользователей Windows.

Step 1

Download and Install MAMP

MAMP is the OSX version of the one-click Apache-MySQL-PHP install.  If you’re on a PC, you want to try out XAMPP instead (XAMPP also comes in an OSX flavor, but I haven’t personally tried it).  In any case, you’ll want to download one of these two programs and follow the instructions for installation.

Step 2

Download Code Igniter

Code Igniter is an MVC based PHP framework created by the makers of Expression Engine – a CMS/blogging platform. What (I think) sets CI apart from other frameworks like Cake or Zend is its soft learning curve and strong documentation. The involved community doesn’t hurt either. You’ll want to download it in order to continue to step 3.

Step 3

Install Code Igniter

Once you’ve downloaded and unzipped CI, you’ll want to copy the folder over to your server root. If you’re using MAMP – the default is /Applications/MAMP/htdocs. At that point, you should change the folder name from CodeIgniter_1.7.1 to whatever you want to use to describe your site. I changed my folder name to ‘ci’. That’s it for installation.

Step 4

Setup Your MySQL database

Odds are, you’re following this tutorial so you can build a dynamic site in PHP. Dynamic nearly always means database, so you’ll have to create one. You can do this in MAMP by switching over to your running instance and clicking on ‘Open start page’. From the links on top, you can select ‘phpMyAdmin’. Otherwise, you can probably just copy and paste this: http://localhost:8888/MAMP/frame.php?src=%2FphpMyAdmin%2F%3Flang%3Den-iso-8859-1&language=English. From there, create a new database (I’ve called mine ‘ci’).

A note here: CI can handle sessions either with or without the database. My personal preference is to use the database, because it provides greater functionality, and you don’t have to worry about hitting your 4k cookie size limit. Enabling database sessions is fairly simple in CI, and we’ll get to that further down. However, you’ll first need to add the sessions table to the database. The default name of the sessions table is ‘ci_sessions’ – you can change this here and in the settings, but remember to do it in both places or this won’t work. In this case, I’m going to keep it the same. Code Igniter provides the SQL you’ll need here, so you can click on the ‘SQL’ tab in phpMyAdmin and copy/paste the code in. Here it is:

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id)
);

Step 5

Edit your Code Igniter Settings

From this point, you’ll want to edit your CI settings to match your environment. The first thing we’ll do is open up the system->application->config folder. In here are all the files that run the configuration settings.

config.php

On line 14, you’ll see this:

$config['base_url']	= "http://example.com/";

You’ll want to change it to your own install directory. You can also edit your vhosts file to have it match your live url… but that’s a more advanced procedure and not part of this tutorial. So in this case, I’ve changed it to:

if($_SERVER['HTTP_HOST']=='имя_локального_домена:8888')
    $config['base_url']    = "http://имя_локального_домена:8888/";
else
    $config['base_url']    = "http://имя_рабочего_домена/";

имя_локального_домена = loco; имя_рабочего_домена = loco.ru (если сделать одинаковыми, то наблюдается конфликт и сайт из интернета не открывается вообще).

The next portion of code you might need to change is from lines 234-242, and it looks like this:

$config['sess_cookie_name']		= 'ci_session';
$config['sess_expiration']		= 7200;
$config['sess_encrypt_cookie']	= FALSE;
$config['sess_use_database']	= FALSE;
$config['sess_table_name']		= 'ci_sessions';
$config['sess_match_ip']		= FALSE;
$config['sess_match_useragent']	= TRUE;
$config['sess_time_to_update'] 	= 300;

This is where you can setup your sessions to use the database, as outlined above. Just change $config['sess_use_database'] to true.

There are other settings in config.php you can modify to suit the framework to your needs, but those are the only ones I typically use.

database.php

This is the file where we’ll set our database access – location, username, password, and database name. It looks like this:

if($_SERVER['HTTP_HOST']=='имя_локального_домена:8888')
    $active_group = "local";
else
    $active_group = "default";

$active_record = TRUE;
    
$db['default']['hostname'] = "mysql_имя_хоста";
$db['default']['username'] = "имя_пользователя_БД";
$db['default']['password'] = "пароль_пользователя_БД";
$db['default']['database'] = "имя_БД";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

$db['local']['hostname'] = "localhost:8889";
$db['local']['username'] = "root";
$db['local']['password'] = "root";
$db['local']['database'] = "srv12683_ci";
$db['local']['dbdriver'] = "mysql";
$db['local']['dbprefix'] = "";
$db['local']['pconnect'] = TRUE;
$db['local']['db_debug'] = TRUE;
$db['local']['cache_on'] = FALSE;
$db['local']['cachedir'] = "";
$db['local']['char_set'] = "utf8";
$db['local']['dbcollat'] = "utf8_general_ci";

Пояснение значений:

    hostname - Наименование хоста вашего сервера баз данных. Чаще всего это "localhost".
    username - Имя пользователя для подключения к базе данных.
    password - Пароль для подключения к базе данных.
    database - Имя базы данных, к которой необходимо подключиться.
    dbdriver - Тип базы данных. К примеру: mysql, postgre, obdc и т.д. Должен указываться в нижнем регистре.
    dbprefix - Опциональный префикс таблиц, который добавляется к их именам при работе с запросами Active Record. Это позволяет работать нескольким дистрибутивам CodeIgniter в пространстве имён одной базы данных.
    pconnect - TRUE/FALSE (boolean) - использовать ли постоянные соединения.
    db_debug - TRUE/FALSE (boolean) - Должны ли ошибки базы данных выводиться на экран.
    cache_on - TRUE/FALSE (boolean) - Включено ли кеширование запросов. Смотрите также Кеширование запросов.
    cachedir - Абсолютный путь на сервере к директории кеширования запросов.
    char_set - Наименование кодировки, в которой работает база данных.
    dbcollat - Сопоставление символов, которое используется базой данных.
    port - Номер порта базы данных. Сейчас используется только в драйвере Postgre. Чтобы использовать это значение, вам необходимо добавить строку в файл конфигурации базы данных.

MAMP automatically sets your username and password to root, and your MySQL port to 8889, so can copy and paste the above for working locally. You can also create a second set of these variables called $db['production'] for example, with your live settings in it. When you are ready to move the site, all you’ll need to do is change your $active_group variable to ‘production’.

autoload.php

Code Igniter gives you the ability to add only the libraries and functionality you need for your project. The autoload.php file lets you name which files you want across the application. You can read more about it on the CI site, but one thing you’ll likely want to do right away is enable your database and session libraries to load. This is done on line 42:

$autoload['libraries'] = array('database','session');

Odds are you’ll also want to load the URL helper, that allows you to enter shortcut functions for some common locations (like the base url). You can do this on line 54:

$autoload['helper'] = array('url');

.htaccess

CI doesn’t come with an .htaccess file, but odds are you’ll want to add additional folders to your root ‘ci’ folder while keeping the rest of your site secure by redirecting most requests through the main index.php file. So, create a file named .htaccess in your main ‘ci’ folder. Вот пример .htaccess:

Options +FollowSymLinks
Options -Indexes

DirectoryIndex index.php

RewriteEngine on
RewriteBase /
#RewriteCond %{HTTP_HOST} ^loco\.ru$ [NC]
#RewriteRule ^(.*)$ http://loco.ru/$1 [R=301,L]

RewriteCond $1 !^(index\.php|images|pics|js|robots\.txt|public)
RewriteCond %{REQUEST_URI} !\.(css│js│jpg│gif│png)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA] 

What this does in tell the Apache URL-rewrite module to redirect any request that isn’t in the above list to the index.php file of our ‘ci’ directory. I’ve added images,css, and js folders to the ‘ci’ directory so I can start adding assets there.

That’s all there is to it. At this point, you should have all of the basic resources you need to start developing a sweet app in Code Igniter. When you are ready to move your site to a production server, just remember to change your database settings, base url in config.php, and the RewriteRule in your .htaccess file, and you’ll be up and running in no time.


almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.

Вы можете почитать все статьи от almix'а.



Другие статьи по этой теме:

Комментарии (0)     Подпишитесь на RSS комментариев к этой статье.