Source

erlang_php_session_storage / session_handler.erl

Full commit
% See http://obvioushints.blogspot.com/2009/12/erlang-as-session-storage-for-php.html

-module(session_handler).
-author("Alvaro Videla videlalvaro at gmail.com").

-behaviour(gen_server).

-export([start/0, stop/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
  terminate/2, code_change/3]).

-export([read/1, write/2, destroy/1, gc/1]).


start() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop()  -> gen_server:cast(?MODULE, stop).

read(SessId) -> gen_server:call(?MODULE, {read, SessId}).
write(SessId, Data) -> gen_server:call(?MODULE, {write, SessId, Data}).
destroy(SessId) -> gen_server:call(?MODULE, {destroy, SessId}).
gc(Timeout) -> gen_server:call(?MODULE, {gc, Timeout}).

-record(state, {table}).

init([]) -> 
  TableId = ets:new(session, [set]),
  {ok, #state{table=TableId}}.

handle_call({read, SessId}, _From, #state{table=TableId}=State) -> 
  error_logger:info_msg("read called ~p.~n", [SessId]),
  Reply = 
  case ets:lookup(TableId, list_to_binary(SessId)) of
    [{_, Data}] -> Data;
    _ -> ""
  end,
  {reply, Reply, State};

handle_call({write, SessId, Data}, _From, #state{table=TableId}=State) ->
  error_logger:info_msg("write called ~p ~p.~n", [SessId, Data]),
  Reply = ets:insert(TableId, {list_to_binary(SessId), Data}),
  {reply, Reply, State};

handle_call({destroy, SessId}, _From, #state{table=TableId}=State) ->
  error_logger:info_msg("destroy called ~p.~n", [SessId]),
  Reply = ets:delete(TableId, list_to_binary(SessId)),
  {reply, Reply, State};

handle_call({gc, Timeout}, _From, State) ->
  error_logger:info_msg("gc called ~p.~n", [Timeout]),
  Reply = "GC",
  {reply, Reply, State}.

handle_cast(stop, State) -> {stop, normal, State}.
handle_info(_Info, State) -> 
  error_logger:info_msg("handle_info ~p ~p.~n", [_Info, State]),
  {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.