Communication, information transfer between PHP App and Ruby App

I mainly work in PHP and prefer to do this because there are apparently more jobs in this language, at least in my language (and I'm still pretty new to this, so I want to continue learning the language better ) .. but for some things that I want to do, I need to use the WWW Mechanize library, which does not work with PHP, but does with Ruby (yes, I know that PHP has several alternatives, but I tried them, and they don't work for me so I need to do this), so I would like to write most of my application in PHP, and Then just call Ruby when I need to use this library and then pass the information to PHP, yes, I know that it will be "slow" "but this is not a problem in this case, since this is not a public web application, but simply for business use.

I am wondering what is the best way to pass information between two languages ​​.. I thought about using http POST (like Curl in PHP) to do this, but not sure if this is the most efficient way .. any information is appreciated, thanks

+3
source share
2 answers

There are two different ways to do this:

\ 1. In ruby, configure a non-HTTP server that listens only to "::" (or 127.0.0.1 if you don't like ipv6). Then, every time your PHP script needs to do something, it can connect to the server and pass data to it. This would be the fastest solution because ruby ​​script does not need to be run every time PHP has to do something.

Ruby example:

require 'mechanize'
require 'socket'

def do_mechanize_stuff(command, *args)
  case command
  when 'search_google'
    # search google with args.join(' ')
  when 'answer_questions_on_stackoverflow'
    # answer questions on stackoverflow
    # with mechanize
  end
  'the result to pass to PHP'
end

srv = TCPServer.new '::', 3000

loop do
  Thread.new(srv.accept) do |sock|
    sock.write(
      do_mechanize_stuff *sock.gets.split(' ')
    )
    sock.close
  end
end

Ruby client example: (you need to translate this to PHP)

require 'socket'

# This is a script that searches google
# and writes the results to stdout.

s = TCPSocket.new 'localhost', 3000

s.puts 'search_google how to use a keyboard'

until (r = s.gets).nil?
  print r # a search result.
end

, http://god.rubyforge.org/, .

\ 2. ruby ​​ script exec PHP .

script:

require 'mechanize'

def do_mechanize_stuff(command, *args)
  # ... from previous example
end

do_mechanize_stuff ARGV.shift, ARGV
+4

Architectire (SOA) /Rails . API ( , ): POST/GET, .

+1

Source: https://habr.com/ru/post/1753060/


All Articles