2011년 2월 28일 월요일

facebook App dev

php framework

PHP개발에 관해서 찾다가..


이라는 글을 찾았습니다.
오호~ PHP에도 Framework라는 개념이 있더군요.
그래서 PHP Framework를 선택하기 위해서 이런저런 자료를 조사 하면서 조사한 내용을 정리 해 볼려고 합니다.

Ruby On Rails의 영향으로 웹 프로그래밍에서 Framework에 대한 관심이 폭발적으로 늘어나게 되고, PHP에서도 Framework에 지원이 활발하게 진행이 되었나 봅니다. 그리고 위의 글에서와 같이 여러개의 PHP Framework가 생겨 나게 되고, 현재 주류를 이루고 있는 Framework는 4개 정도로 압축 되는거 같습니다.

  • Zend Framework
  • CakePHP
  • Code Igniter
  • Symfony

자료를 찾아서 나름대로 특징을 정리 해 봤습니다.



Zend Framework
zend framework

  1. PHP의 핵심 기부자인 Zend Technologies에서 개발.
  2. PHP5 만 지원
  3. 다양한 DB 데이터베이스 추상화
  4. 확장가능한 MVC 모델 지원
  5. HTML 폼 렌더링 및 유효성 검사 지원
  6. 유연한 캐싱 서브 시스템
  7. 엄격한 코드 테스트를 거친 안정된 코드
  8. 국제화 지원
  9. 많은 양의 예제 지원
  10. new BSD 라이센스
  11. 국내 사용자 포럼을 못 찾았음.

CakePHP

  1. PHP4, PHP5 지원
  2. 구조화 된 MVC모델 지원
  3. 데이터베이스 인터랙션과 간략화한 쿼리를 위한 CRUD 가 통합됨
  4. 애플리케이션 스캐폴딩
  5. 보기좋은 맞춤 URL 의 요청 디스패처
  6. 빠르고 유연한 템플릿 기능 (PHP 문법, 각종 헬퍼 포함 )
  7. AJAX, 자바스크립트, HTML 폼을 위한 각종 뷰 헬퍼
  8. 보안, 세션, 리퀘스트 등을 처리하는 컴포넌트
  9. 유연한 뷰 캐시
  10. 유연한 접근 제한 목록
  11. 자료 검사 기능 내장
  12. 국제화 지원
  13. MIT License
  14. CakePHP 한국 사용자 모임.

Code Igniter

  1. PHP4, PHP5 지원
  2. 설치가 간편하다.
  3. 잘 정리된 문서
  4. 확장이 용이하다.
  5. MVC 모델 지원
  6. 간견한 문법
  7. 다른 프레임워크에 비해 빠른 속도
  8. 국제화 지원
  9. BSD 라이센스
  10. CodeIgniter 한국 사용자 모임
  11. CodeIgniter 한글 메뉴얼


Symfony

  1. PHP5만 지원
  2. 간단한 템플릿과 도우미(Helpers)
  3. 캐시 관리
  4. 기본 골격 (CRUD/Admin generator)
  5. 스마트 URLs (routing policy)
  6. 국제화 지원
  7. 객체모델과 MVC 분리
  8. MIT License
  9. 국내 사용자 포럼을 못 찾았음.

주요 특징들의 위와 같습니다. 여기저기서 찾은 자료들이라서 ^^;; 잘 비교가 되지 않네요..



실행 속도 비교

그리고 다음은 중요한 실행 속도 입니다.
4개의 Framework를 모두 비교한 자료는 찾지를 못했습니다.
먼저 Zend Framework, CakePHP, CodeIgniter를 비교한 결과를 그래프로 그려 봤습니다.


그래프에서 높을 수록 빠른 겁니다. CodeIgniter가 독보적인 선두를 보이고 있습니다. 그리고 Zend Framework와 CakePHP가 뒤를 따르고 있습니다.
그런데 Symfony에 대한 비교가 없어서, CakePHP, Zend Framework, Symfony의 속도를 비교를 검색해 봤는데.. 최근에 비교한 내용을 찾을 수가 없었습니다.
그래서 결국 이상한 나라의 언어(글을 보고 어떤 나라인지 유추를 못 하겠네요 ^^;;;)로 된 페이지를 찾았습니다. 언어는 해독 불가(-_-;;) 이지만, 그래프는 볼 수 있어서.. 첨부 합니다.

위와 같은 그래프가 나오더군요.. 결국 Symfony가 4개의 프레임워크 중에서 가장 늦은 속도를 가지고 있는거 같습니다.



그럼 대세는?
마지막으로 Google Trends의 그래프를 첨부하겠습니다.
검색의 빈도를 통해서 어떤게 관심을 받는지 보는건데,
검색 결과로 봐서는 cakephp가 1위 이지만, 가장 후발 주자로 시작한 codeingniter가 많이 따라잡고 있는 것으로 볼 수 있습니다.



여기 까지 PHP Framework를 소개하는 포스팅을 마칠려고 합니다.
비교는 여기까지이고 PHP의 Framework의 선택은 개발자의 몫이 아닐까 합니다.

php framework CI

지난번 포스티에서 PHP Framework를 비교 한적이 있습니다.
그 4개의 Framework중에서 제 마음에 드는건 CodeIgniter더 군요. 그리고 몇 일 공부 한 짧은 지식을 정리해 볼까 합니다.


프레임워크를 왜 사용하는가?

프레임워크는 재사용 가능한 클래스와 개발 시간을 단축 할 수 있는 기능을 제공합니다. 프레임워크를 통해서 개발 함으로 인해서 원치 않은 코드의 개발을 최소화 할 수 있다. codeIgniter의 예로 들면, database 접근,email 전송, form 데이터검증(validation),세션관리, 이미지 처리, XML-RPC 등 이 외에도 다양한 기능을 제공합니다. 이런 기능들을 특별히 구현 할 필요 없이 프레임워크에서 제공해 주는 것을 사용하면 됩니다. 이런 것을 통해서 많은 개발 시간을 단축 시킬 수 있습니다.



CodeIgniter를 선택한 이유.

CodeIgniter는 매우 가볍은 프레임워크입니다. PHP Framework 비교 글에서 언급하였다 시피 codeIgniter는 PHP Framework중에서 최고의 속도를 자랑합니다.
학습이 쉽습니다. 뿐만 아니, 친절한 도움말이 제공됩니다.(한글번역본도 있습니다.).
MVC 패턴을 지원합니다. 비니지스로직 계층과 표현계층이 분이 되어 있고 디자이너와 협업시에는 템플릿파일에 최소한의 코드로 제작 할 수 있습니다.
그리고 무료 입니다 ^ ^;; 가장 중요한가요?

아래 내용은 CodeIgniter 제공하는 기능 목록 입니다. CodeIgniter 사용자 가이드에서 퍼왔습니다 ^^;;;.

  • 모델-뷰-컨트롤러 기반
  • PHP 4 에 적합
  • 엄청 가벼움
  • 여러플렛폼을 지원하는 완벽한 데이터베이스 클래스들
  • 액티브레코드(Active Record Database) 지원
  • 폼과 데이터의 검증
  • 보안과 XSS 필터링
  • 세션 관리
  • Email 전송클래스. 첨부파일지원.HTML/Text 지원.다양한프로토콜 지원(sendmail, SMTP, and Mail) 등.
  • 이미지 관리 라이브러리(자르기,크기조절,돌리기 등).GD , ImageMagick, NetPBM 지원
  • 파일 업로드 클래스
  • FTP 클래스
  • 로컬라이즈(Localization)
  • 페이지네이션
  • 데이터암호화
  • 벤치마크
  • 전체페이지 캐싱
  • 에러로깅
  • 성능측정(Application Profiling)
  • 스캐폴드(Scaffolding)
  • 캘린더클래스
  • User Agent 클래스
  • Zip 압축
  • 템플릿엔진
  • 트랙백(Trackback)
  • XML-RPC 라이브러리
  • 단위테스트
  • 검색엔진에 색인되기 좋은 URLs
  • 유연한 URI 라우팅
  • 후킹,클래스확장,플러그인 지원
  • 방대한 헬퍼 라이브러리

이런 엄청난 기능을 제공해 주는데, 사용 안 할 수 없겠죠?
그럼 시작해 보겠습니다.


1. CodeIgniter 다운로드

당연히 다운로드 받아야 겠죠? CodeIgniter 홈페이지에 가서 받으시면 됩니다. 현재 가장 최신은 1.7.1입니다.



2. 설치 및 구조 좀 살펴 보기.

CodeIgniter의 압축을 푸시면 위와 같은 구조가 나옵니다. 참 많죠? -_-;;
이 파일들은 Apache에 PHP가 설치되고, MySQL이 설치된 환경의 디렉토리에 복사 하시면 됩니다. 여기서는 ci라는 폴더를 만들어서 복사해서 넣겠습니다.

그러면, 이 많은 폴더에 뭐가 들어 있는지 간략하게 적어 보겠습니다.
아래부터는 CodeIgniter를 CI라고 쓰겠습니다. 코드이그나이터 라고 쓸려니.. 영타도 길고 해서.. 줄여서 쓸랍니다.
  • system : CI 작업을하게 되는 모든 파일입니다.
    • application : 응용 프로그램 폴더 입니다. 현재 작업 하시는 공간이라고 보시면 좋습니다.
      • config : 응용프로그램의 환경설정. 자동로드 및 데이터베이스 연결, 라우트등 대부분의 설정을 합니다.
      • controllers : 응용프로그램 컨트롤.
      • errors : 응용프로그램에 대한 오류 페이지 템플릿.
      • helpers : 헬퍼 저장소.
      • hooks : CI의 코어 파일을 변경하지 않고 작동방식을 변경할때 사용
      • language : 다국어 지원을 위한 언어 폴더.
      • libraries : 응용프로그램 사용자 라이브러리.
      • models : 모델. 데이터베이스와 연동하여 사용하기 위한 클래스.
      • views : 뷰. 웹페이지 디자인 및 템플릿.
    • cache : 캐시 라이브러리에 의해 생성된 캐시가 저장 됨.
    • codeigniter : codeingiter
    • database : 데이터베이스 드라이버와 클래스.
    • fonts : 이미지 편집 라이브러에 사용할 글꼴.
    • helpers : CI에서 제공하는 기본 핼퍼.
    • language : CI에서 기본제공되는 언어
    • libraries : 라이브러리
    • logs : 지정된 로그가 기록 됨.
    • plugin : 플러그인
    • scaffolding : 데이터베이스 조작 클래스.
  • user_guide : 사용자 도움말. 홈페이지에 있는 도움말과 동일한 내용입니다.
  • index.php : CI의 시작점. 시스템 및 응용프로그램의 폴더 이름을 변경 할 수 있습니다.


3. CI 동작 개념


먼저 CI 한글 사용자 가이드의 내용을 보시겠습니다.

  1. The index.php 는 프론트콘트롤러(front controller)로 동작하여 CI가 동작하기 위한 기반리소스들을 초기화 합니다.
  2. 라우터모듈(Routing)은 http 요청을 분석하여 어떤 동작을 해야할지를 결정합니다.
  3. 캐쉬파일이 있다면 그파일을 바로 브라우저로 보내고 일반적인 동작절차는 무시합니다.
  4. 보안모듈(Security)은 프로그램 컨트롤러가 로딩 되기전에 HTTP 요청및 어떤 사용자 전송데이터든지 모두 필터링합니다.
  5. 컨트롤러(Application controller)는 사용자 요청을 처리하기 위해 모델을 로드하고,코어라이브러리,플러그인,헬퍼 및 필요한 다른 리소스들을 로드 합니다.
  6. 최종적으로 뷰모듈(View)이 렌더링되어 브라우저로 전송됩니다. 캐싱이 활성화 되어이다면 먼저 캐쉬(Cashing)하여 다음번 요청에 사용할 수 있도록 합니다.

위와 같은 처리를 거쳐서 어플리케이션이 돌아 가게 됩니다. 참 복잡하죠? ^^;; 하지만 걱정하지 마세요.. 대부분의 기능은 프레임워크에서 담당해 주고 있습니다. 개발자는 약간의 손만 거들 뿐~ ^^;


이번 포스팅에서는 이 정도의 간단한 구조라고 생각하시면 됩니다. Controller를 제작해서 Model을 통해서 DataBase의 정보를 빼오고 View를 통해서 출력 하는 구조 입니다.

// 아이고 -_-;;; 아직 코딩 시작도 못 했는데.. 생각보다 내용이 길어 졌네요 ^^;; 코딩은 다음글로~ 졸리네요 ^^

cakephp vs codeigniter

I almost fear putting this kind of post together as it's bound to pull the fanatics (in the negative sense of the word) out of the woodworks. Right off the bat, let me just say that I've tried to be as fair and honest in this assessment and I've tried to keep it just to the facts while interjecting what my preferences are.

I'm pitting these two frameworks against each other but there really isn't a clear winner. Each has its strengths and weaknesses and ultimately falls to what your preference for certain features might be.

Why compare these two?

CakePHP and CodeIgniter are quite similar in their approach on a number of things, including their support for PHP4. Any mention of one inevitably leads to someone mentioning the other.

They both attempt to create an MVC architecture which simply means they separate the (data) Model from the Controller (which pulls data from the model to give to the view) from the View (what the user sees).

They both use Routing which takes a URL and maps it to a particular function within a controller (CakePHP calls these actions). CodeIgniter supports regular expressions for routing, whereas you'll have to wait until CakePHP 1.2 for that feature. Correction: CakePHP 1.1 supports regular expression for routing but it's not detailed in the manual and is getting updated in 1.2.

They both support Scaffolding which is an automated way of generating a view based on the model. Scaffolding is meant for simple prototyping and CodeIgniter takes it a step further by requiring a keyword in the URL to even access the scaffolding. I'm guessing one could omit the keyword, leaving this feature essentially optional. I prefer not to have to use the keyword as I sometimes build personal projects not intended for public eyes and using a keyword would be a nuisance.

And the list goes on...
Approach to Simplicity

I believe much of CodeIgniter's appeal is its simplicity in its approach. Most of the work is done in the controller, loading in libraries, getting data from the model, and pulling in the view. Everything is in plain sight and you can really see how things work.

CakePHP's simplicity comes via automation (euphemistically referred to as "automagic"). It makes the coding process quicker but harder to figure out "what is going on" without popping your head into the core. For me, I like to understand how everything works and I've had to poke around under the hood more than once. For people just getting started, things probably look a little daunting.
Working with Models

CodeIgniter's model handling is fairly straightfoward and basically allows you to mimic a standard SQL query with a few straightforward commands like these examples:

$query = $this->db->getwhere('mytable', array(id => $id), $limit, $offset);

$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
$query = $this->db->get();

Note: the method chaining in the second part of this example is only available in PHP5.

You can also create a model object, load it in and build custom methods to handle a custom task. You'd want to do this in the model and not the controller to help isolate code into the MVC silos.

CakePHP takes a slightly different route by automatically loading in the model that matches the current controller (controllers tend to be named similarly to the models they are associated with). You can turn off this automated loading and even assign different models that should be loaded by the controller instead.

CakePHP also takes things further by establishing all the model associations for you, allowing for some really easy querying. For example, assuming I'm in a controller named post_controller, I could do the following:

$this->Post->Comment->findAllByPostId($id)

I chose this particular query because it shows two different concepts. The first is the fact that I can access the Comment model via the Post model (assuming I've defined that association in the Post model). The second is the fact that I have a method called findAllByPostId. CakePHP allows records to be grabbed via findByX and findAllByX queries where X is equal to the field name you're trying to find.

Where I think Cake shines is in its ability to pull in all associated data automatically. Take the following query as an example:

$this->Post->findById($id)

This query would automatically pull in all the comments associated with this Post. Really handy stuff.
Validation

When working with models, you'll inevitably have to handle data validation. Data validation in CodeIgniter is handled via a validation class. A set of rules get defined and assigned to the validation object. The validation object automatically (I assume) validates the data passed via the URL or form. From there, you can decide how that gets handled. The validation class can also help automate some of the process of setting error messages for specific fields.

CakePHP handles its validation through the model itself in one of two ways. The first uses a single test against each field defined in a validate variable declared in the model. This works okay for simple stuff but it quickly becomes a cumbrance. Beyond simple validation, I take advantage of the beforeSave callback to perform any custom validation, invalidating any fields that fail.

It's a toss up for me as to which one "wins". CakePHP 1.2 will have its validation system reworked a bit to allow for more flexibility.
Views

CakePHP handles this fairly well by using a default layout (which you can easily switch at runtime). The layout has two variables be default: title_for_layout and content_for_layout. Each action automatically links to a particular view which gets spat into place. Again, it's the "automagic" approach. As long as you name your files a specific way, controllers automatically get linked to models and views. It's easy enough to override all of this, too, and define your own layouts or view files. There's no convenient way to get the generated view data, however, making custom built caching mechanisms difficult to implement.

CodeIgniter takes a very straightforward approach: like include files, almost. Each file gets loaded in and processed. There's a templating class but it doesn't simplify things much beyond the built-in view handling. You can mimic the CakePHP approach by always including the header and footer calls but it's not as seamless. CodeIgniter offers hooks allowing view and caching mechanisms to be overridden and replaced with a custom system.
Out of the Box Features

CodeIgniter in my mind wins this hands down with classes for FTP, Email, File Uploading, XMLRPC, Zip encoding and more.

CakePHP on the flip side comes pretty light but tries to make up for it using the Bakery. You can, like CodeIgniter, easily drop in 3rd party classes for any features you might need. Interestingly, although I haven't tried it, you could probably drop in many of the CI classes into CakePHP without issue.
Auto-loading

CakePHP allows for application-wide changes to be done via the base application controller that all other controllers inherit from. Likewise, you can create global model methods using the application model file. However, you can fine tune things at the controller level using any of the controller-level callbacks (beforeFilter, afterFilter and beforeRender). Things like auto-loading helpers and components can also be specified easily at the individual controller level.

CodeIgniter allows for the auto-loading of helpers, libraries and plugins but does this application-wide.
Documentation

Documentation is key to understanding any framework well enough to develop within it.

CodeIgniter has a complete list of all components with each method and property documented within. CI also has forums and a wiki which feature a lot of user-submitted code.

CakePHP, on the other hand, isn't as well organized. The manual is starting to show its age with some sections not really going much beyond what the API offers. Because of the format of the original documentation, you can also get it in other formats such as CHM and PDF. CakePHP has the Bakery which contains user-submitted articles, components, etc. The dev team also hangs out heavily on the IRC channel (#cakephp at irc.freenode.net). Finally, there's the CakePHP Google Group which is pretty active.
Final Verdict

I'm a pretty pragmatic individual and I honestly feel that these two frameworks have a lot going for them. They take a much simpler approach to application development than the complexity that is something like Symfony.

I'm still personally a fan of CakePHP over CodeIgniter for much of the "automagic" that I mentioned. And it's shortcomings have been getting addressed with each new iteration (1.2 will be a considerable leap over 1.1 but it will still be awhile before it's released).
Notes

This comparison was based on the documentation for CodeIgniter 1.5.2 and having used CakePHP 1.1. I have specifically avoided the subject of performance due to the amount of time required to design, develop and test such a thing.

Create Facebook applications with CodeIgniter

Create Facebook applications with CodeIgniter

Integrating the Facebook SDK

Thomas Myer (tom@tripledogs.com), Consultant, Triple Dog Dare Media

Summary: Learn how to incorporate the Facebook SDK into the CodeIgniter framework, using the available functions to create applications.

Date: 24 Aug 2010
Level: Intermediate
PDF: A4 and Letter (348KB | 12 pages)Get Adobe® Reader®
Also available in: Korean Japanese

Activity: 17044 views
Comments: 2 (View | Add comment - Sign in)

Average rating 4 stars based on 16 votes Average rating (16 votes)
Rate this article

This article shows you how to get the sample Facebook application working with the CodeIgniter framework for PHP. There are plenty of really great articles out there on Facebook development, of course, and a handful of good ones on using CodeIgniter to build applications, but this one takes into account the latest PHP SDK made available by Facebook.

Instead of showing you how to take an existing wrapper library for the Facebook SDK, you will learn how to easily wrap the SDK yourself and then use it in a quick way. This article also shows you all the steps you need to take to register your application with Facebook and how to set up CodeIgniter to start working with Facebook, and it covers the basic stuff you might encounter during this process.

As this article covers quite a bit of territory, a few prerequisites will help you keep up. First, you need to know something about PHP and CodeIgniter. You don't need to know a great deal, but some familiarity will help you get started. You also need access to your own publicly available web server. Applications like the one you're going to create always reside on their own server and are then served up in iframes inside Facebook: Merely coding from localhost won't work here. Last but not least, you need a Facebook account, because you're required to register your application with Facebook.

The basics

Before getting into details, here's a quick overview of Facebook applications and CodeIgniter.

Facebook application basics

You can build different kinds of Facebook applications, including mobile and web applications—the focus of this article. Basically, all a Facebook application really consists of is an iframe that runs on Facebook.com and calls code on your server.

The code on your server needs to follow a few rules for integrating with Facebook sessions and using the right functions to access various functionality (like listing your friends or events you've RSVP-ed to), but that's about it. You can add all kinds of functionality to your application, such as saving different data into database tables, to add value to the Facebook experience.

If you do things right, your Facebook application will be something that Facebook users will sign up for and tell others about, which means that you will need to think a bit about bandwidth issues. Every time you get a new user or someone interacts with your application, the Facebook servers make a request that hits your server, so plan for that.

What kinds of applications can you build on Facebook? Take a look at the Facebook Developer Showcase (see Resources for a link), and you'll see hundreds of live applications in a variety of categories—news, sports, social good, utilities, reviews, local, and more. For example, the Pandora application integrates the popular personalized music service with Facebook. Facebook users can now easily share their music discoveries with their friends and further personalize their enjoyment of music. Similarly, the IMDb Facebook application allows Facebook users to further engage with their favorite movies, actors, and directors and to share their thoughts directly with Facebook friends.

The SimplyHired application combines the power of Facebook friend networks and recommendations with a job search engine to get customized job recommendations. The TripAdvisor application allows Facebook users to "like" properties and destinations and to share key aspects of their travel experience with their friends.

In this article, there won't be space for more than a basic application, but if you want to be a Facebook application developer, you would do well to study the market and see what's out there.

CodeIgniter basics

CodeIgniter is a model-view-controller (MVC) framework for PHP created by EllisLab. As of this writing, it's at version 1.7.2. Although many MVC frameworks are available for PHP (such as Symfony and CakePHP), the chief differentiator that sets CodeIgniter apart is the flexibility it derives from being so lightweight.

With CodeIgniter, as with other MVC frameworks, you divide your code into different functional areas:

  • Models contain any and all code that relates to your database and other data structures. If you had a table called pages, you'd have a model for it and functions within that model for selecting, creating, updating, and deleting records from that table, among other things.
  • Views contain all your display and UI elements—your JavaScript code, CSS files, HTML, and even PHP.
  • Controllers hold it all together. Each function in a controller represents a destination or route. If you had a destination called /about, your controller would have a function called about().

If you haven't worked with an MVC framework before, these three bullet points offer little clue as to the power behind this organizational scheme. Once you start thinking in terms of MVC, your perspective about and attitude toward PHP development changes radically.

For example, instead of tucking database query code in every available nook and cranny of your project, you organize all of it into models. And to select a page from your database table, you use a function from the pages model.

Similarly, if you need to update the look and feel of a certain page, you work with the views. You don't mess around with the controller. Likewise, the controller is where you add destinations and other controlling code for your application; you don't put any of that stuff in your model.

Unlike other MVC frameworks, there are no strict naming conventions for your models, tables, and controllers in CodeIgniter. For example, you don't have to name your table in the plural form (pages) and your model in the singular (page) to tie the two together. Your database tables don't have to contain certain fields with certain names, either: If you don't have a primary key field named id, the world won't end.

Furthermore, you can choose to use as much or as little of the framework as you need to get the job done. Typically, your application will have a series of controllers, all of which will pull data from models and then display data in views. In some cases, though, your projects will only have controllers and views—a perfect solution if you're building a static web site without a database back end.

Another interesting fact about CodeIgniter is how easy it is to integrate with other code. In most cases, if you want to integrate an external SDK, simply add it to the plugins folder with a specific naming convention (for example, in this article, you rename the facebook.php library file to facebook_pi.php), and you're ready to go.


Getting started

So, let's get started with your first Facebook application written with CodeIgniter. This is a multistep process that requires a bit of setup; by the end of it, you'll have everything you need to create a Facebook application.

To install and configure CodeIgniter, perform the following steps:

  1. Download and install CodeIgniter (see Resources).
  2. Open the downloaded .zip file, and extract the contents to a publicly available web server.

    You can deploy CodeIgniter into the root of an existing domain, into a sub-domain, or to a folder off the root of an existing domain.

  3. Open the system/application/config/config.php file in a text editor, and update the $config['base_url'] variable so that it points to where you installed CodeIgniter. Be sure to upload the changes to the server.
  4. Test CodeIgniter by opening a browser and visiting the URL that houses the CodeIgniter application (for instance, example.com/test or test.example.com).

    You should see the generic message, "Welcome to CodeIgniter!" If you don't, you've missed something along the way. Reinstall CodeIgniter and start over.

    It's important that you run this test, as you need to be able to confirm that your CodeIgniter base code is working properly and isolate any problems that might occur with the connection between Facebook and your server.

    Note: If you're having trouble seeing the generic message from CodeIgniter, it might be that you're having DNS trouble—particularly if this is a new domain or sub-domain. If that's the case, you might need to give it some time before you move on to the next step.

  5. Go to Facebook.com/developers and set up a new application.

    If this is the first time you've done this, perform the following steps:

    1. Click Allow to provide access to the application.
    2. On the Developer page, click Set Up New Application.
    3. On the Create Application page, enter a name for your application (it can be anything you want), select Agree, and then click Create Application, as shown in Figure 1.

      Figure 1. Creating an application
      The 'Create Application' screen in Facebook, showing a field for              'Application name,' radio buttons for agreeing or disagreeing to the Terms,              and a 'Create Application' button

    4. On the Edit Application page, on the Basic tab, note the application ID, API key, and secret—these are unique to each Facebook application, and you'll need this information to do your job.

      Figure 2. The Basic tab
      Screen shot of the Edit Application page, Basic tab

    5. Type a description for your application, and add an icon, logo, and other information. (You can also come back and do this later.)
    6. Click the Canvas tab, and enter the canvas page URL (that is, the destination on Facebook.com that people will go to get your application) and the canvas callback URL (the URL where you installed CodeIgniter plus a directory path to a controller.)

      In the example in Figure 3, the canvas callback URL is http://www.example.com/index.php/home/, which is where you'll create a home controller in your installation and where the application will do its heavy lifting.



      Figure 3. The Canvas tab
      Screen shot of the Edit page, Canvas tab, showing the fields 'Canvas              Page URL' and 'Canvas Callback URL.'

    7. Click the Connect tab (see Figure 4), and enter your connect URL.

      This URL should be the same as the canvas callback URL you entered earlier. Note that if your application lives in a sub-domain (for example, foo.example.com), type your base domain in the Base Domain field (that is, example.com).



      Figure 4. The Connect tab
      The Edit page, Connect tab, showing the Facebook connect settings

    8. Click Save Changes. You should see a summary page if all has gone well (see Figure 5).

      Figure 5. The summary page
      A sample page indicating at the top that your changes were saved.

  6. Download the PHP SDK (see Resources).

    The download contains a src/facebook.php file (this is the main library) and an examples/example.php file.

  7. Create a simple application in CodeIgniter:
    1. Rename the facebook.php file you just downloaded to facebook_pi.php, and put it in the system/application/plugins folder of your CodeIgniter code.

      If no plugins folder exists, create it now and put your newly renamed file in it.

    2. Copy the example.php file into the system/application/views folder.
    3. Open a text editor, and create a simple controller called Home. Copy and paste the code in Listing 1 into that file, and then save it as home.php in the system/application/controllers directory.

      Listing 1. A bare-bones controller
       
      class Home extends Controller {

      function Home()
      {
      parent::Controller();
      $this->load->plugin('facebook');
      }

      function index()
      {
      $this->load->view('example');
      }
      }

      Here, you're creating a home controller so that your route will activate properly. Remember that the Facebook application is looking for example.com/index.php/home, so this particular controller will respond to that request. The index() function will load any requests that come bare to that controller, just like an index.html or index.php file will on a static server.

      When you initiate the class, the constructor loads your Facebook plug-in. (Wait a minute, you ask: When did I create a Facebook plug-in? Remember what you did with the facebook.php file, renaming it to facebook_pi.php and placing it in the plugins folder? That's all you had to do to make it available to CodeIgniter as a plug-in.)

      In the index() function, you simply load the example view (no need to put the .php part in), and all that remains is two minor edits to the example.php file in the views folder.

    4. Load the example.php file into a text editor, and remove the first line—the one that does an include of the facebook.php line. CodeIgniter did that already when you ran $this->load->plugin('facebook');.
    5. Change the lines in Listing 2 to match the application ID and secret you got from Facebook when you created your application.

      Listing 2. Editing the view
       
      // Create our Application instance.
      $facebook = new Facebook(array(
      'appId' => 'some-value',
      'secret' => 'some-other-value',
      'cookie' => true,
      ));

    6. Save your work, and then push your updates to the server.

You've been working hard on the initial setup, and when you get back from your well-earned break, you need to test to make sure you've done everything right.


A final test

As a final test of what you've been doing, simply visit the URL you assigned to your application in Facebook—in other words, the http://apps.facebook.com/YOUR_APP_NAME address. If you've done everything correctly, you should see a page like the one in Figure 6 in your browser (except of course, you'll see your own Facebook data and not mine!). If you don't see such a page or if errors come up, you may need to enable cURL and/or run a version of PHP that supports json_decode(). The Facebook SDK will error out if neither of these is available on your server.


Figure 6. The running application
A screen shot of the author's Facebook application, entitled 'PHP-SDK'

If you want to compare what the raw code looks like outside of CodeIgniter, you can visit fbtest.tripledogs.com—a little sub-domain that I set up that has the raw SDK running without CodeIgniter. If you compare that code with what you have running now, you'll see that it only took a few extra minutes to achieve the same results, but now you've got the power of the CodeIgniter framework at your disposal.


Conclusion

At this point, you know how to get started with your own Facebook application. With any luck, using this approach, you can easily move on to more complex undertakings.


Resources

Learn

Get products and technologies

Discuss

2011년 2월 27일 일요일

페이스북에는 있지만 트위터에는 없는 5가지 특징.


얼마전 포스트에서 트위터에는 있지만 페이스북에는 없는 5가지 특징을 포스팅한 적이 있습니다. 오늘 포스팅에서는 반대로 페이스북에는 있지만 트위터에는 없는 5가지 특징을 설명해 드리겠습니다.

먼저 읽어보시면 좋은포스트 : 트위터에는 있지만 페이스북에는 없는 5가지 특징.
트위터와 페이스북을 비교해보고 사용법 안내.


작년 한해동안 소셜네트워크 서비스는 우리나라에서 큰폭으로 확장되었습니다.

처음에는 트위터의 확장속도가 빠른거 같더니 최근에는 페이스북의 성장세가 트위터를 앞도하는 모습입니다.
세계적으로 보았을때도 페이스북의 사용인구가 트위터에 비해 2배이상 많은 편이고, 개인적으로 확장성면에서도 페이스북 서비스가 우수하다고 보여집니다.

트위터와 페이스북 비교그림


오늘 포스팅에서는 페이스북에는 있지만 트위터에는 없는 5가지 특징을 살펴보려고 하는데요,

강조그림

지금까지 페이스북과 관련된 많은 포스팅들에서 언급되었던 설명들이기 때문에 "포스트뷰" 블로그를 자주 찾아주시는 분들에게는 새롭거나 흥미면에서 다소 떨어질 수도 있겠네요.

하지만, 오늘 포스팅의 의미는 앞으로 보다 심도있게 페이스북을 탐험하기 위한 가이드 정도로 보아주셨으면 좋겠네요.

페이스북의 각각의 특징들은 하나 내지는 그 이상의 포스팅으로 엮어도 전혀 가볍지 않은 주제들로 앞으로 "포스트뷰" 블로그에서 하나씩 다뤄보려고 합니다.




1. 페이스북에서는 누구나 광고를 진행할수 있다.

페이스북 광고의 특징과 효과에 대해서는 "포스트뷰"의 많은 포스팅에서 다루고 있습니다.


페이스북 광고모습
페이스북에서 진행되는 광고그림


트위터를 이용하시는 많은 분들이 트위터 회사의 수익모델에 대해서 궁금하실 겁니다. 사용자 대부분이 트윗덱,시스믹등의 어플들을 이용해서 트위터 계정에 접속하기 때문에 트위터는 당췌 광고를 하기가 힘든 구조입니다.

이부분 때문에 트위터에서도 어떻게 하면 외부어플이 아닌 트위터 계정페이지로 사용자를 끌어드릴까 노심초사 하고 있는걸로 압니다. 그래서 트위터 계정 사용자 스킨도 개편하고 했지요.




광고부분이나 수익모델 측면에서 페이스북이 트위터보다 우수한 것은 사실입니다.

강조표시

페이스북의 구조상 대다수의 어플들이 페이스북 계정내에 설치되어야 하는 구조이고 페이스북 계정페이지를 서핑하다보면 자연스럽게 페이스북 광고에 접하는 시간은 많아지겠지요.


지난년도에 발생한 페이스북 매출이 한화로 2조원 정도라고 밝혔는데 수익의 대다수가 광고수익으로 이루어져 있습니다.




2. 페이스북에서는 소셜게임을 즐길수 있다.

트위터와 페이스북을 둘다 운영하고 있는 필자가 느낌으로

강조

트위터는 정보의 파급속도가 빠르고 페이스북은 친밀도가 강한거 같습니다.


그리고 페이스북은 사용자를 잠시도 편안하게 가만두지 않는다는 것입니다.

수없이 많은 초대와 친구들의 요청, 그리고 새로이 친구관계를 맺도록 끊임없이 부추겨서 분위기를 조성한다는 것입니다.

페이스북 계정 로그인시 나타나는 친구들의 추천과 요청들

페이스북의 수많은 추천과 요청들.

위의 그림처럼 페이스북 계정에 로그인하게 되면 친구들의 많은 액션들을 보여주면서 사용자도 움직이기를 권유하는 모습입니다.

트위터와 페이스북의 특징중 2번째는 요청란에 보여지는 게임요청 항목입니다.

페이스북에서는 친구에게 다양한 게임을 요청해서 함께 즐길수 있습니다.

소셜게임을 요청한 친구들 모습


게임요청 메뉴를 클릭하면 저에게 게임을 신청한 친구들의 모습이 보여집니다.

강조표시

"동의" 버튼을 클릭하게 되면 게임신청한 친구와 해당게임을 진행하게 됩니다.


이런 게임들을 SNG (Social Networks Game) 라고 불려지고 있는데, 소셜네트위크 게임중에 가장인기 있는 게임은 아래에 보시는 "징가" 사에서 제작한 "팜빌" 이라는 게임입니다.


"징가"라는 회사는 소셜네트워크 게임만 전문으로 제작하는 게임회사인데, 페이스북의 성장세와 더블어 현재 시가총액이 "EA"를 앞선다고 하니 대단하네요.


소셜게임 팜빌 실행화면

팜빌 게임 실행화면

게임내용은 간단하게 말해서 "농사짓는 게임" 입니다. 하지만, 한가지 특징은 페이스북 친구들과 함께 즐길수 있는 게임이라는 것이죠.

강조표시
우리나라에서 탄생한 온라인 게임이 화려한 그래픽 함께 온라인으로 몬스터를 때려잡는 게임이라면, 팜빌 같은 소셜네트워크 게임은 페이스북 친구라는 관계속에서 서로 협력해서 하나의 프로젝트를 이루어 간다는 개념이 많아 보이네요.

소셜네트워크 게임이 상당히 중독성이 강해서 미국에서는 가정주부들이 가사일은 돌보지 않고 소셜네트워크 게임에만 열중한다고 해서 사회문제로 까지 대두된다고 하니 소셜네트워크 게임의 성장성은 크다고 보여집니다.





3. 페이스북에는 블로그를 위협하는 노트가 있다.


얼마전 포스트에서 트위터와 페이스북이 블로그를 대체할수 있는가에 대해서 고민해 본 적이 있습니다.
포스트를 보고 많은 분들이 아직은 SNS가 블로그를 대체하기는 시기상조라는 것이 중론이었습니다.




필자의 생각으로는 페이스북의 노트는 현재도 블로그를 위협하는 강력한 존재라고 감히 말씀드립니다.
앞으로 2번의 포스팅을 통해서 페이스북의 노트가 왜 강력한지는 차차 설명드리겠습니다.

강조표시

오늘은 트위터와 페이스북의 차이점을 말씀드리는 포스팅이기 때문에 간략하게 설명드리면 트위터는 스마트폰의 단문메세지에 최적화 되어 있기 때문에 140자의 표현 한계를 가지고 있습니다.

반면에 페이스북은 글을 작성하는 데 글자수에 대한 제약이 특별히 없습니다, 하지만 대부분이 담벼락이나 뉴스피드에 긴글을 작성하지는 않기 때문에 페이수북에서 긴글의 장문은 따로 작성해서 보관할 수 있도록 "노트"라는 공간을 마련해 두었습니다.


페이스북에서 작성된 노트모습

페이스북 노트 작성모습



4. 페이스북은 카페처럼 그룹을 통해서 친구끼리 모일수 있다.

페이스북 그룹은 트위터에서 활성화되어 있는 트윗애드온즈 "당" 모임들하고 유사한 면이 있습니다.


그런데 한가지 재미있는 특징은 포털들의 카페나 트위터 모임의 "당"들이 개설해 놓고 가입을 기다리는 반면,
페이스북 그룹은 특이하게도 그룹을 개설한 다음에 친구들을 부르면 자동으로 그룹에 가입되는 방식입니다.


필자의 의지와 상관없이 가입된 그룹들

필자 "샤프심" 의 의지와는 전혀상관없이 가입된 그룹들. 색연필 표시를 누르면 그룹을 만들수 있습니다.

지금까지 인터넷 모임에서는 보기 힘든 방식이었는데, 주커버그가 뭔 생각으로 이렇게 만들었는지는 모르겠지만,...

강조표시

필자의 개인적인 느낌에는 굉장히 유용하고 효과적인 마케팅 툴일거라는 느낌이 옵니다.
느낌을 구체화 시켜서 다음번에 포스팅으로 엮어 보겠습니다.




5. 페이스북은 페이지를 개설해서 홈페이지처럼 이용이 가능하다.



페이스북에서 가장 중요하고도 핵심적인 것이 페이지라고 생각됩니다.
페이스북 페이지는 페이스북의 특징인 "좋아요" 버튼과 수많은 어플리케이션들이 결합해서 큰 힘을 가질것으로 전망됩니다.



페이스북 페이지 거론할때마다 나오는 코카콜라 페이스북 페이지 입니다.


코카콜라 페이스북 페이지모습


보통 페이스북 페이지를 접속하게 되면 "담벼락"이 나오지만 코카콜라 페이스북 페이지는 일반 홈페이지처럼 초기페이지가 꾸며져 있습니다.

강조표시

이것은 페이스북 페이지 어플리케이션 중에서 "FBML" 이라는 어플리케이션으로 제작된 것입니다.


"FBML" 어플리케이션에 대한 설명은 페이스북 페이지와 홈페이지의 장단점을 분석하는 포스트에서 자세히 안내해 드리겠습니다.

이상으로 페이스북에는 있지만 트위터에는 없는 5가지 특징을 살펴보았는데, 너무 광범위하고 흥미진진한 이야기들이라서 오늘은 간략하게 소개만 드리겠습니다. 한가지 특징마다 다양한 이야기들을 기대해 주세요~~



저작자 표시 비영리 변경 금지
샤프심의 페이스북 노트 설명이미지, 클릭하면 바로가기