<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Celalsahinaltinisik on Medium]]></title>
        <description><![CDATA[Stories by Celalsahinaltinisik on Medium]]></description>
        <link>https://medium.com/@celalsahinaltinisik?source=rss-b0527e80d405------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C34KtADoX09YaXnJDJ-UAg@2x.jpeg</url>
            <title>Stories by Celalsahinaltinisik on Medium</title>
            <link>https://medium.com/@celalsahinaltinisik?source=rss-b0527e80d405------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:10:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@celalsahinaltinisik/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Write Yourself Chat With Nodejs & Socket-IO]]></title>
            <link>https://medium.com/@celalsahinaltinisik/how-to-write-yourself-chat-with-nodejs-socket-io-f4c9e40b3adc?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c9e40b3adc</guid>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 05:30:25 GMT</pubDate>
            <atom:updated>2024-10-10T05:31:22.507Z</atom:updated>
            <content:encoded><![CDATA[<p>I want to share the web chat application I made a long time ago with nodejs. I hope it will be useful.</p><p>Happy reading.</p><p>I used the socket-io package to send and capture data instantaneously. The content of the code was set to be simple and easy to install.</p><p>First, we create a structure where we will listen to the requests coming from the server side.</p><blockquote>Not: Each time you refresh the web page, a new connect is created. The old connection dies.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY3kNRpWgJA3-PwkiAr5dA.png" /><figcaption>Docker Logs</figcaption></figure><p>First, we install socket.io on the http server. I set the port information that the server will run as 3000. You can enter the any value you want..</p><pre>const express = require(&#39;express&#39;)<br>const http = require(&#39;http&#39;)<br>const {Server} = require(&#39;socket.io&#39;)<br>const cors = require(&#39;cors&#39;)<br>const port =  3000;<br>const app = express()<br>app.use(cors())<br><br>const server = http.createServer(app)<br>const io = new Server(server, {<br>  cors: {<br>    origin: &#39;http://localhost:&#39; + port,<br>    methods: [&#39;POST&#39;, &#39;GET&#39;]<br>  }<br>})<br><br>server.listen(port, () =&gt; {<br>  console.log(&#39;Socket.IO server running at http://localhost:${port}/&#39;);<br>});</pre><p>We start connect with socket server.</p><p>Now, after room selection, we send our request to join the join_room parameter.</p><pre>$(&#39;#rooms&#39;).on(&#39;change&#39;, function (e) {<br>  let optionSelected = $(&quot;option:selected&quot;, this);<br>  var valueSelected = this.value;<br>  if (!valueSelected) {<br>   formDisable(true);<br>   return;<br>  }<br>  socket.emit(&#39;join_room&#39;, {room_list: roomList, room: valueSelected});<br>  formDisable(false);<br> });</pre><p>Now we meet the requests from the join_room parameter. Here the user joins the room chooses. Exit from other rooms is provided.</p><pre>  socket.on(&#39;join_room&#39;, data =&gt; {<br>    // get objects<br>    const {room_list, room} = data;<br>    room_list.forEach(rooms =&gt; {<br>      // if room equal to rooms. dont leave<br>      if (rooms == room) {<br>          return;<br>      }<br>      socket.leave(rooms);<br>      console.log(&#39;leave room:&#39; + rooms);<br>    });<br>    //<br>    socket.join(room);<br>    console.log(&#39;join: &#39; + room);<br>  });</pre><p>Now the user can send his message to the room of his choice. Requests are transported with send_server.</p><pre>form.addEventListener(&#39;submit&#39;, function(e) {<br>   e.preventDefault();<br>   if (input.value) {<br>    var rooms = $(&#39;#rooms&#39;).find(&quot;:selected&quot;).val();<br>    socket.emit(&#39;send_server&#39;, {name: name, msg: input.value, room: rooms});<br>    input.value = &#39;&#39;;<br>   }<br>  });</pre><p>There is a code listening send_server on server.js. This code is responsible for forwarding the incoming information to the relevant room.</p><pre>  socket.on(&#39;send_server&#39;, data =&gt; {<br>    console.log(data);<br>    io.to(data.room).emit(&#39;client&#39;, data.name, data.msg);<br>  });</pre><p>The ‘client’ parameter that carries requests and sending data.</p><pre> socket.on(&#39;client&#39;, function(name, msg) {<br>  const item = document.createElement(&#39;li&#39;);<br>  item.textContent = name + &#39; &#39; + msg;<br><br>  messages.appendChild(item);<br>  window.scrollTo(0, document.body.scrollHeight);<br> });</pre><p>We listen to messages from the room. We print incoming messages on the screen.</p><p>We are listtinig and data output coming message from this code block into join room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_nNPA0ECHFZr9Qe0eS7gg.png" /></figure><p>I hope my short article was explanatory and simple. Thanks for reading. The source and project link are shared below.</p><p>Project Link: <a href="https://github.com/celalsahinaltinisik/socket_io_Nodjes">github</a></p><p><a href="https://github.com/celalsahinaltinisik/socket_io_Nodjes">https://github.com/celalsahinaltinisik/socket_io_Nodjes</a></p><p>References:</p><p><a href="https://socket.io/get-started/chat">socket-io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c9e40b3adc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I was wrote video transfer with UDP Protocol!]]></title>
            <link>https://medium.com/@celalsahinaltinisik/how-i-was-wrote-video-transfer-with-udp-protocol-29cc83c42258?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/29cc83c42258</guid>
            <category><![CDATA[udp-protocol]]></category>
            <category><![CDATA[data-transfer]]></category>
            <category><![CDATA[vi̇deo]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[live-streaming]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 17:12:11 GMT</pubDate>
            <atom:updated>2024-03-19T17:12:11.490Z</atom:updated>
            <content:encoded><![CDATA[<p>Before reading this articlei I recommend you to read my previous medium article. <a href="https://medium.com/@celalsahinaltinisik/what-is-user-datagram-protocol-udp-2bae2730aad7">Link</a></p><p>Happy reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kfUHoVXXug6u5Rml" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Firstly explain content of <a href="https://github.com/celalsahinaltinisik/golang/blob/main/udpsocket/udpsender.go">udpsender.go </a>.</blockquote><p>We provide udp connection with DialUDP() func using the net package. ip and port information is up to you. When we stop sending bytes, we close the connection with defer conn.Close().</p><p>With the gocv package, we access our camera using the OpenVideoCapture() func. İf you set 0 value. we can access camera 1 of our computer. When I did it on my macbook, I also got an image from the iphone camera. You may need to disconnect your Mac from your iPhone</p><p>The NewWindow() func allows us to name the opened display window.NewMat() will create a func mat object and hold the image data.</p><p>Now we enter the loop and capture the image with Read() func. IMShow() loads the image captured with the func into the window. With sendLargeData() func, we transmit the captured image as bytes over udp.</p><p>First we fragment the Byte image. I set it to 1024 bytes. The reason I do this is because there is a max size limit. We send the 1024 byte data with Write() func. Of course, I compress the data I send here with gzip(). Finally, we send the “EOF” separator after the fragmented data. With this “EOF” separator I can manage the image frame in the byte data on the listener side.</p><blockquote>last step, let’s publish the image. <a href="https://github.com/celalsahinaltinisik/golang/blob/main/udpsocket/udplistener.go">udplistener.go</a></blockquote><p>We start listening to our connection point with ListenUDP() func in our listener file. When the work is stopped, we close the connection with defer. The gocv package opens a new window with the NewWindow() func. We will transfer the byte data we receive to this window as an image. We will defined our variable named buffer as 1024 byte slice. We enter a loop and get a byte slice of 1024 bytes from our udp connection with ReadFromUDP() func. The deCompresse func gzip package decompresses the compressed data. You will see this when you examine the code. We collect the byte data we receive in our sliceData variable.</p><p>We provide “EOF” control with hasEOF() func. we obtain the full byte of the image. We can now convert the data we append to the sliceData variable into an image. Firstly, we delete our “EOF” separator with removeEOF() func and add it to receivedData2 variable. We obtain a “Mat” object with the NewMatFromBytes() func of the gocv package. Now we transfer the image we captured to the window we have opened with IMShow() func.</p><p>I hope my short article was explanatory and simple. Thanks for reading.</p><p><a href="https://github.com/celalsahinaltinisik/golang/tree/main/udpsocket">GitHub Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29cc83c42258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is User Datagram Protocol (UDP)?]]></title>
            <link>https://medium.com/@celalsahinaltinisik/what-is-user-datagram-protocol-udp-2bae2730aad7?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bae2730aad7</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[udp]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 18:55:55 GMT</pubDate>
            <atom:updated>2023-12-06T18:55:55.080Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello world… I will talk briefly about UDP. UDP protocol main feature decresing server and client between wait time. So, What is wait time? I will give http protocol example. Client was request firstly wait answer from server. Server was run and a return response to client. That is no has on udp protocol. Server and Client don’t use ack direct reading data.</p><figure><img alt="datocms-assets.com" src="https://cdn-images-1.medium.com/max/1024/1*tDlS-Pgri4DrCorr9aw68g.jpeg" /><figcaption>datocms-assets.com</figcaption></figure><p>Data will be lost occur. Udp has max data size. UDP maximum packet size will be 65,535 bytes.If you pass max size. An error oncour.</p><p>Solution, splitting byte package and one by one sending. You will sum all byte to server and processing.</p><p>Example. 100 person want to join one train wagon. But one wagon can hold max 20 person. It is need 5 wagon.</p><p>That’s why we use splitting byte. Data may be lost and delay. Byte calculation important process.</p><p>I writed example code with golang. I will explain code detail next time.</p><p>Plase for example code below click to link</p><p>Project Link: <a href="https://github.com/celalsahinaltinisik/golang/tree/main/udpsocket">github</a></p><p><a href="https://github.com/celalsahinaltinisik/golang/tree/main/udpsocket">https://github.com/celalsahinaltinisik/golang</a></p><p>References:<br><a href="https://pkg.go.dev/gocv.io/x/gocv@v0.21.0">gocv</a><br><a href="https://github.com/hybridgroup/gocv/tree/release/cmd">hybridgroup</a><br><a href="https://pkg.go.dev/net">net</a><br><a href="https://pkg.go.dev/compress/gzip">gzip</a><br><a href="https://pkg.go.dev/bytes">bytes</a><br><a href="https://pkg.go.dev/">For Other Golang Packages</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bae2730aad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ Publish & Consume With Golang]]></title>
            <link>https://medium.com/@celalsahinaltinisik/rabbitmq-publish-consume-with-golang-26412784b6e5?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/26412784b6e5</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 16:10:35 GMT</pubDate>
            <atom:updated>2023-07-30T16:10:35.708Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello… I will token about how we use rabbitmq with golang. We will see first useing publish with api service. Firstly we will a http server generating. Now useing how can a simple way http server with package “net/http” I show you.</p><p>server.go file. You can see below content of file.</p><pre>package main<br><br>import (<br> &quot;net/http&quot;<br><br> &quot;github.com/celalsahinaltinisik/route&quot;<br>)<br><br>func main() {<br> http.HandleFunc(&quot;/&quot;, route.Routeing())<br><br> http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>Now we did import package “net/http”. Firstly we listened port then processed all routing.</p><p>/route/route.go</p><pre>package route<br><br>import (<br> &quot;errors&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;reflect&quot;<br> &quot;strings&quot;<br><br> controller &quot;github.com/celalsahinaltinisik/controllers&quot;<br> &quot;golang.org/x/text/cases&quot;<br> &quot;golang.org/x/text/language&quot;<br>)<br><br>func urls(s map[string]string, str string, method string) (bool, string) {<br> for i, v := range s {<br>  if i == str &amp;&amp; v == method {<br>   return true, cases.Title(language.English).String(strings.Replace(str, &quot;/&quot;, &quot;&quot;, -1))<br>  }<br> }<br> return false, &quot;&quot;<br>}<br><br>func Routeing() http.HandlerFunc {<br> return func(w http.ResponseWriter, r *http.Request) {<br>  routings := map[string]string{&quot;/home&quot;: &quot;GET&quot;, &quot;/publish&quot;: &quot;POST&quot;, &quot;/consume&quot;: &quot;GET&quot;}<br>  log.Println(r.URL.Path, r.Method)<br>  check, funcName := urls(routings, r.URL.Path, r.Method)<br>  log.Println(funcName)<br>  if !check {<br>   http.Error(w, &quot;404 not found.&quot;, http.StatusNotFound)<br>   return<br>  }<br><br>  // controller.Publish(w, r)<br>  m := controller.Functions{}<br>  Call(m, funcName, w, r) //todo<br> }<br>}<br><br>func Call(m interface{}, name string, params ...interface{}) (result []reflect.Value, err error) {<br> f := reflect.ValueOf(m).MethodByName(name)<br> if len(params) != f.Type().NumIn() {<br>  err = errors.New(&quot;The number of params is not adapted.&quot;)<br>  return<br> }<br> in := make([]reflect.Value, len(params))<br> for k, param := range params {<br>  in[k] = reflect.ValueOf(param)<br> }<br> result = f.Call(in)<br> return<br>}</pre><p><strong>func urls():</strong> This function provides the request from the api service equal to the method and url. This function compares the URL and HTTP method of the incoming request with the URLs and methods defined in a specific map. If there is a match, it returns true and the name of the corresponding function (in lowercase) found in the map. Otherwise, it returns false and an empty string.</p><p><strong>func Routeing(): </strong>The URL and method of the incoming request are compared with this map, and if a suitable match is found, the name of the corresponding function is retrieved. Then, the Call function is used to call the appropriate controller function.</p><p><strong>func Call():</strong>This function is used to call a specific method of a given object (instance of a structure or class). Here, a given structure (object) and method name are used to call a specific method. The function associated with the method name is called using the reflect package.</p><p>The functions defined in the controller package are used here as the targets of the routing process, so that the web application responds to requests.</p><p>What I want to do here is to call our simple and dynamically defined methods.</p><p>Now let’s create our controller file where our functions run.</p><p>/controller/homecontroller.go</p><pre>package controller<br><br>import (<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br><br> errors &quot;github.com/celalsahinaltinisik/exceptions&quot;<br> rabbitmqconnect &quot;github.com/celalsahinaltinisik/rabbitMQ&quot;<br>)<br><br>type Functions struct{}<br><br>func (m Functions) Home(w http.ResponseWriter, r *http.Request) {<br> fmt.Fprintln(w, &quot;home&quot;)<br> log.Println(r.Body)<br>}<br>func (m Functions) Consume(w http.ResponseWriter, r *http.Request) {<br> fmt.Fprintln(w, &quot;consume&quot;)<br> rabbit := rabbitmqconnect.RabbitMQ{QueueName: &quot;defaultqueuue&quot;}<br> rabbit.Consume()<br>}<br><br>func (m Functions) Publish(w http.ResponseWriter, r *http.Request) {<br><br> body, err := io.ReadAll(r.Body)<br> errors.FailOnError(err, &quot;Failed to readall body request&quot;)<br> rabbit := rabbitmqconnect.RabbitMQ{Body: string(body), QueueName: &quot;defaultqueuue&quot;}<br> rabbit.Puplish()<br></pre><p>Here I defined routing for APIs and as you can see there are two functions named publish and consume. The JSON data sent from the API service is sent to RabbitMQ. Then the consume API service is called to process the data in the queue. You can increase the number of goroutines while processing the data. See Golang documentation for usage.</p><p>For RabbitMQ, I created three files: connection.go, consume.go, and publish.go under my RabbitMQ folder. I thought it would be straightforward in terms of usage and invocation.</p><p>connection.go</p><pre>package rabbitmqconnect<br><br>import (<br> errors &quot;github.com/celalsahinaltinisik/exceptions&quot;<br> amqp &quot;github.com/rabbitmq/amqp091-go&quot;<br>)<br><br>func ConnectMQ() (*amqp.Connection, *amqp.Channel) {<br> conn, err := amqp.Dial(&quot;amqp://rabbitmq:rabbitmq@127.0.0.1:5672&quot;)<br> errors.FailOnError(err, &quot;Failed to connect to RabbitMQ&quot;)<br> // defer conn.Close()<br> ch, err := conn.Channel()<br> errors.FailOnError(err, &quot;Failed to open a channel&quot;)<br> // defer ch.Close()<br> return conn, ch<br>}<br><br>func CloseMQ(conn *amqp.Connection, channel *amqp.Channel) {<br> defer conn.Close()    //rabbit mq close<br> defer channel.Close() //rabbit mq channel close<br>}</pre><p>publish.go</p><pre>package rabbitmqconnect<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br><br> errors &quot;github.com/celalsahinaltinisik/exceptions&quot;<br> amqp &quot;github.com/rabbitmq/amqp091-go&quot;<br>)<br><br>type RabbitMQ struct {<br> Body      string<br> QueueName string<br>}<br><br>func (r *RabbitMQ) Puplish() {<br><br> conn, ch := ConnectMQ()<br> defer CloseMQ(conn, ch)<br><br> // log.Println(ch)<br> q, err := ch.QueueDeclare(<br>  r.QueueName, // name<br>  false,       // durable<br>  false,       // delete when unused<br>  false,       // exclusive<br>  false,       // no-wait<br>  nil,         // arguments<br> )<br><br> errors.FailOnError(err, &quot;Failed to declare a queue&quot;)<br><br> ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br> defer cancel()<br><br> body := r.Body<br> err = ch.PublishWithContext(ctx,<br>  &quot;&quot;,     // exchange<br>  q.Name, // routing key<br>  false,  // mandatory<br>  false,  // immediate<br>  amqp.Publishing{<br>   ContentType: &quot;text/plain&quot;,<br>   Body:        []byte(body),<br>  })<br> errors.FailOnError(err, &quot;Failed to publish a message&quot;)<br> log.Printf(&quot; [x] Sent %s\n&quot;, body)<br>}</pre><p>consume.go</p><pre>package rabbitmqconnect<br><br>import (<br> &quot;log&quot;<br><br> errors &quot;github.com/celalsahinaltinisik/exceptions&quot;<br>)<br><br>func (r *RabbitMQ) Consume() {<br><br> conn, ch := ConnectMQ()<br> defer CloseMQ(conn, ch)<br><br> // log.Println(ch)<br> q, err := ch.QueueDeclare(<br>  r.QueueName, // name<br>  false,       // durable<br>  false,       // delete when unused<br>  false,       // exclusive<br>  false,       // no-wait<br>  nil,         // arguments<br> )<br> errors.FailOnError(err, &quot;Failed to declare a queue&quot;)<br><br> msgs, err := ch.Consume(<br>  q.Name, // queue<br>  &quot;&quot;,     // consumer<br>  true,   // auto-ack<br>  false,  // exclusive<br>  false,  // no-local<br>  false,  // no-wait<br>  nil,    // args<br> )<br> errors.FailOnError(err, &quot;Failed to declare a queue&quot;)<br><br> k := make(chan bool)<br><br> go func() {<br>  for d := range msgs {<br>   log.Printf(&quot;1.Received a message: %s&quot;, d.Body)<br>   // d.Ack(false)<br>  }<br> }()<br><br> // go func() {<br> //  for d := range msgs {<br> //   log.Printf(&quot;2.Received a message: %s&quot;, d.Body)<br> //   // d.Ack(false)<br> //  }<br> // }()<br><br> log.Printf(&quot; [*] Waiting for messages. To exit press CTRL+C&quot;)<br> &lt;-k<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_bsROJNwRzwjxbvpbwCihA.jpeg" /></figure><p>Project Link: <a href="https://github.com/celalsahinaltinisik/golang">github</a></p><p><a href="https://github.com/celalsahinaltinisik/golang">https://github.com/celalsahinaltinisik/golang</a></p><p>References</p><ul><li><a href="https://pkg.go.dev/">Go Packages - Go Packages</a></li><li><a href="https://www.rabbitmq.com/tutorials/tutorial-one-go.html">RabbitMQ tutorial - &quot;Hello World!&quot; - RabbitMQ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26412784b6e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node JS MVC Pattern]]></title>
            <link>https://medium.com/@celalsahinaltinisik/node-js-mvc-pattern-fa59e0f7131e?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa59e0f7131e</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Wed, 24 May 2023 19:01:56 GMT</pubDate>
            <atom:updated>2023-05-24T19:01:56.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Node js express ile mvc pattern yapısının oluşturulması adına sizlere yardımcı olacağını düşündüğüm bir örnek paylaşmak istiyorum. Gerekli kurulumları yaptığınızı varsayarak adımlara geçiyorum.</p><p>İlk olarak package.json dosyamızın içeriğini oluşturalım.</p><pre>{<br>  &quot;name&quot;: &quot;csa_docker_web_app&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;Node.js csa mvc my app&quot;,<br>  &quot;author&quot;: &quot;CSA &lt;ornek@example.com&gt;&quot;,<br>  &quot;main&quot;: &quot;src/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/index.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;bcryptjs&quot;: &quot;^2.4.3&quot;,<br>    &quot;dotenv&quot;: &quot;^10.0.0&quot;,<br>    &quot;ejs&quot;: &quot;^3.1.6&quot;,<br>    &quot;express&quot;: &quot;^4.17.1&quot;,<br>    &quot;express-session&quot;: &quot;^1.17.2&quot;,<br>    &quot;joi&quot;: &quot;^17.9.2&quot;,<br>    &quot;mongodb&quot;: &quot;^5.3.0&quot;,<br>    &quot;mongoose&quot;: &quot;^6.0.3&quot;,<br>    &quot;passport&quot;: &quot;^0.4.1&quot;,<br>    &quot;passport-local&quot;: &quot;^1.0.0&quot;,<br>    &quot;socket.io&quot;: &quot;^4.6.1&quot;<br>  }<br>}</pre><p>Şimdi package.json içeriğimizi gösterdiğim şekilde veya farklı isimlendirmeler ile değiştirebilirsiniz. Burada farkedeceğiniz üzere “src” dizini içersinde kodumuzu geliştireceğiz.</p><p>İlk olarak models, views ve controllers dizinlerimizi oluşturalım. Ardından server’ı başlatmak için “index.js” dosyamızı oluşturalım.</p><pre><br>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const { init } = require(&#39;./models/table&#39;)<br>const routes = require(&#39;./routes&#39;)<br>const path = require(&quot;path&quot;);<br><br>const app = express()<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));<br>app.set(&quot;view engine&quot;, &quot;ejs&quot;);<br>app.use(bodyParser.json())<br>app.use(routes)<br>// Constants<br>const PORT = 3000;<br>const HOST = &#39;0.0.0.0&#39;;<br><br>init().then(() =&gt; {<br>  console.log(&#39;starting server on port 3000&#39; + __dirname)<br>  app.listen(PORT, HOST, () =&gt; {<br>    console.log(`Running on http://${HOST}:${PORT}`);<br>  });<br>})</pre><p>Burada neler yaptık kısaca bahsetmek gerekirse. Models dizininde db connect ve crud işlemlerinin gerçekleşti dosyayı dahil ediyorum. ardından “init” fonksiyonu ile db connection gerçekleştirilip server başlatılıyor.</p><p>Sonra app.set ile global değişkenlere “view engine” ve view dosya yolunu set ediyoruz. Yapılan isteklerin öncesinde karşılanması için “routes.js” dosyamızı use methoduna dahil ediyoruz.</p><p>Routes dosyamızı oluşturalım.</p><pre>const express = require(&#39;express&#39;)<br>const Joi = require(&#39;joi&#39;)<br>const {insertItem} = require(&#39;./models/table&#39;)<br>const { rules } = require(&#39;./Requests/TabeStoreRequest&#39;)<br>const {<br>  registerView<br>} = require(&quot;./controllers/registerController&quot;);<br><br>const router = express.Router()<br>router.get(&quot;/register&quot;, registerView);<br><br>router.post(&#39;/save&#39;, (req, res) =&gt; {<br>  let rule = rules(req)<br>  if (rule.error) {<br>      res.status(400).json(rule.error.message).end()<br>      return<br>  }<br>  let {name} = req.body<br>    let save = <br>    {<br>      name: name,<br>      created_at: new Date(),<br>      updated_at: new Date(),<br>    }<br>    insertItem(save)<br>    .then(() =&gt; {<br>      res.status(201).end()<br>    })<br>    .catch((err) =&gt; {<br>      console.log(err)<br>      res.status(500).end()<br>    })<br>})<br><br>module.exports = router</pre><p>“register” adresine yapılacak istek ile ilgili sayfamız yüklenecek. Bu sayfadan yapılacak bir “save” isteği ile validasyon kontrolü ardından kayıt işlemimizi yapacağız.</p><p>Son olarak controllers dizini içersindeki “registerController.js” dosyamızı oluşturalım.</p><pre>const registerView = (req, res) =&gt; {<br>    res.render(&quot;register&quot;, {<br>    } );<br>}<br>module.exports =  {<br>    registerView<br>};</pre><p>Bu dosyamızda views dizini içersindeki dosyamızı çağırıyoruz. Örnek register.ejs dosyamız. Bu sayfada form arayüz oluşturup “/save” url adresine istek atabilirsiniz.</p><pre>&lt;%- include(&#39;layout.ejs&#39;); %&gt;<br>&lt;h1&gt;Hello CSA&lt;h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Son olarak models dizini içersinde “table.js” dosyamızı oluşturalım.</p><pre>const { MongoClient, ObjectId } = require(&#39;mongodb&#39;)<br><br>const connectionUrl = &#39;mongodb://root:example@localhost:27017&#39;<br>const dbName = &#39;game&#39;<br>const collectionName = &#39;tables&#39;<br><br>let db<br><br>const init = () =&gt;<br>  MongoClient.connect(connectionUrl, { useNewUrlParser: true }).then((client) =&gt; {<br>    db = client.db(dbName);<br>  })<br><br>const insertItem = (item) =&gt; {<br>  const collection = db.collection(collectionName)<br>  return collection.insertOne(item)<br>}<br>module.exports = { init, insertItem }</pre><p>Kodu incelediğinizde “index.js” içersinde server başlatıldığında init methodu ile mongo db bağlantısı sağlanmakta. Sonrasında controllers dosyamızda insertItem methodunu çağırdığımız yerde kayıt işlemini gerçekleştiriyoruz. Temel mvc pattern dosya yapımızı oluşturmuş olduk. Umarım yardımcı olmuştur.</p><p><em>Kodları buraya sadeleştirerek aktarmaya çalıştım. Bazı yerler eksik kalmış olabilir.</em></p><p>Son olarak dosya yapısının görseli;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*qRf66AOO2h727uDLyNoZCw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa59e0f7131e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vendor içersindeki kütüphane dosyalarını geçersiz kılmak (Override)]]></title>
            <link>https://medium.com/@celalsahinaltinisik/vendor-i%C3%A7ersindeki-k%C3%BCt%C3%BCphane-dosyalar%C4%B1n%C4%B1-ge%C3%A7ersiz-k%C4%B1lmak-override-c20dbd901e03?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/c20dbd901e03</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[composer]]></category>
            <category><![CDATA[override]]></category>
            <category><![CDATA[packagist]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 07:53:17 GMT</pubDate>
            <atom:updated>2022-12-29T07:53:17.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Kod yazarken kütüphaneleri hepimiz kullanıyoruz. Kullandığımız kütüphane için yayınlanan versiyonlarda hata olabiliyor. Bir sınıf içerisinde kullandığımız method sorunlu olabiliyor. Yeni versiyonu beklemek istemiyorsunuz ve hatayı ezmek istediniz. İşte burada ilgili dosyayı override ediyoruz.</p><blockquote>Örneklemeyi laravel freamwork üzerinde anlatacağım. Composer ile yüklediğiniz tüm kütüphaneler için geçerlidir.</blockquote><p>Örneğimi vendor altındaki “laravel” paketlerinden “Illuminate/Support” kütüphanesindeki “Str.php” dosyası için uygulayacağım. Composer.json doyamızın içersinde “autoload” anahtarımızın içersine aşağıdaki satırları ekliyoruz.</p><pre>&quot;autoload&quot;: {<br>        &quot;psr-4&quot;: {<br>            &quot;App\\&quot;: &quot;app/&quot;,<br>            &quot;Database\\Factories\\&quot;: &quot;database/factories/&quot;,<br>            &quot;Database\\Seeders\\&quot;: &quot;database/seeders/&quot;<br>        },<br>        &quot;exclude-from-classmap&quot; : [<br>            &quot;vendor/laravel/framework/src/Illuminate/Support/Str.php&quot;<br>        ],<br>        &quot;files&quot; : [<br>            &quot;app/Overrides/Str.php&quot;<br>        ]<br>    }</pre><blockquote><em>exclude-from-classmap: Geçersiz kılmak istediğimiz sınıfın dosya yolunu belirliyoruz.</em></blockquote><p>Override işlemi için yeni dosyayı kütüphaneden kopyalıyoruz ve “app” içersinde tanımlıyoruz. Artık son adımda “dump-autoload” çalıştırmamız gerekiyor.</p><blockquote><em>composer dump-autoload</em></blockquote><p>Bu adım ile dosyalar tekrardan optimize edildi ve vendor altındaki Str.php dosyamızı ezmiş olduk. Artık “app” dizini altındaki sınıfımızı istediğimiz şekilde düzenleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njvbsAmrYx2aNGfg_kvvLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6la4dpm2yJbRVt1Uy3N85g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c20dbd901e03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eloquent Paket Kullanımı ve Routing]]></title>
            <link>https://medium.com/@celalsahinaltinisik/eloquent-paket-kullan%C4%B1m%C4%B1-ve-basit-routing-aa1a63063527?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1a63063527</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[paket-kullanımı]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[routing]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 11:57:49 GMT</pubDate>
            <atom:updated>2022-11-08T10:46:22.365Z</atom:updated>
            <content:encoded><![CDATA[<p>Eloquent laravel tarafından kullanılan ve veritabanını soyutlayarak nesnesel ilişkiyi kurmanıza imkan sağlayan yapıdır. Bu tip yapıların genel adı ORM(Object Relation Mapping) dir. Laravel framework üzerinde hazır gelen bu yapıyı kendi yapınızda(framework olmadan) kulanmak isteyebilirsiniz.</p><p>Günümüzde framework kullanmayan yoktur. Ancak düz(pure) php yazılacaksa da db işlemleri için mutlaka ORM yapılarının kullanılmasından yanayım. Kendi yapınıza dahil edebilmeniz için kurulum, kullanım ve db işlemlerini paylaşıyorum. Umarım faydalı olur.</p><p>İlk olarak bilgisayarınızda <a href="https://getcomposer.org/">composer</a> olmalı. <a href="https://packagist.org/packages/illuminate/database"><em>illuminate/database</em></a><em> </em>paketinin kurulumunu aşağıdaki komut ile projemize dahil edelim. Terminalimizden proje dizinine girip aşağıdaki komutu çalıştıralım.</p><blockquote>composer require illuminate/database</blockquote><p>Komutu çalıştırdıktan sonra paketimizi yüklüyoruz. Ardından “vendor” dizini, “composer.json” ve “composer.lock” dosyaları oluşacaktır.</p><p>Şimdi burada dikkat etmeniz gereken nokta uygulamanızın yapısı olacaktır. Tabi bu durum biraz daha kapsamlı olduğundan basit geçiştireceğim. Ama framework olarak laravel dosya dizinini incelediğinizde “app” dizinini göreceksiniz.Kodunuzu geliştirdiğiniz dizindir. Bende böyle bir dizin oluşturacağım ve “composer.json” dosyasına bu dizini tanıtacağız. Kısacası bu dizinde kodumuzu geliştireceğiz diye tanımlayacağız.</p><pre>{<br>    &quot;require&quot;: {<br>        &quot;illuminate/database&quot;: &quot;9.36.4&quot;<br>        <br>    },<br>    &quot;autoload&quot;: {<br>        &quot;psr-4&quot;: {<br>        &quot;App\\&quot;: &quot;app/&quot;<br>        }<br>    }<br>}</pre><p>Bu tanımı yaptıktan sonra composer dump-autoload komutu ile dizini otomatik tanımlıyor oluyoruz.</p><pre>composer dump-autoload</pre><p>Şimdi app dizinimin içersine “models” ve “controllers” dizinlerimi oluşturup. Ardından models içersinde “database” bağlantımı yapıyorum.</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Capsule\Manager as Capsule;</pre><pre>class Database<br>{<br>    public function __construct()<br>    {<br>        $capsule = new Capsule();<br>        $capsule-&gt;addConnection([<br>         &#39;driver&#39; =&gt; DBDRIVER,<br>         &#39;host&#39; =&gt; DBHOST,<br>         &#39;database&#39; =&gt; DBNAME,<br>         &#39;username&#39; =&gt; DBUSER,<br>         &#39;password&#39; =&gt; DBPASS,<br>         &#39;charset&#39; =&gt; &#39;utf8&#39;,<br>         &#39;collation&#39; =&gt; &#39;utf8_unicode_ci&#39;,<br>         &#39;prefix&#39; =&gt; &#39;&#39;,<br>        ]);<br>        // Setup the Eloquent ORM…<br>        $capsule-&gt;bootEloquent();<br>    }<br>}</pre><p>Şimdi bu database bağlantısını çalıştıracağım dizinde başlatmam gerekiyor. Sizler kendi database bilgilerinizi ilgili alanlara girersiniz. Ana dizinde “index.php” dosyamı oluşturuyorum ve içersinde “vendor” dizinimi çağırıyorum ardından da db bağlantımı başlatıyorum.</p><pre>&lt;?php</pre><pre>use App\Models\Database;</pre><pre>require &#39;vendor/autoload.php&#39;;<br>//Initialize<br>new Database();</pre><p>Şu ana kadar kurulum ve dosya yapımızı oluşturduk aslında. Makaleyi burada bitirmek uzun olmamasını sağlamak adına bölmek isterdim ancak çok doğru olmayacak. Daha anlaşılır olması adına devam etmek ve bu işlemi bir adım daha ileriye taşımak istiyorum. Şimdi yapmak istediğim aslında bir “mvc” design pattern tasarım modelini örnek alarak ilerlemek. Tabi sadece “mc” tarafında bırakacağım.</p><p>Tablosunu oluşturduğum “campaigns” için model dosyasını oluşturacağım. İşte tam burada “orm” dediğimiz olay sizler için devreye gidiyor. Sizler için eloquent otomatik tablo ile aranızda bir katman görevi görerek bağlantıyı sağlamakta.</p><p>Campaign.php dosyamızı models dizini altında oluşturuyoruz.</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Model;</pre><pre>class Campaign extends Model<br>{<br>    protected $guarded = [];<br>}<br></pre><p>Şimdi modelimizi oluşturduk. Olmazsa olmazımız “transaction” durumlarını yönetmemize yaracak olan fonksiyonlarımızı oluşturalım. Eloquent db kayıt durumları(create, update, delete) yönetmek için bize olanak sağlıyor. Model altında “DB.php” dosyasını oluşturuyorum. Bu dosya kayıt işlemlerinde işimize yarayacak.</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Model;</pre><pre>class DB extends Model<br>{</pre><pre>public static function beginTransaction()<br>    {<br>        self::getConnectionResolver()-&gt;connection()-&gt;beginTransaction();<br>    }</pre><pre>public static function commit()<br>    {<br>        self::getConnectionResolver()-&gt;connection()-&gt;commit();<br>    }</pre><pre>public static function rollBack()<br>    {<br>        self::getConnectionResolver()-&gt;connection()-&gt;rollBack();<br>    }<br>}</pre><p>Şimdi “controllers” dizini altında “CampaignController.php” dosyamızı oluşturalım.</p><pre>&lt;?php</pre><pre>namespace App\Controllers;</pre><pre>use Exception;<br>use App\Models\Campaign;<br>use App\Models\DB;</pre><pre>class CampaignController<br>{</pre><pre>public static function save()<br>    {<br>        try {<br>            DB::beginTransaction();<br>             Campaign::create([&#39;name&#39; =&gt; &quot;celal&quot;, &#39;date&#39; =&gt; &quot;2022-10-10&quot;, &#39;file_name&#39; =&gt; &quot;file&quot;]);<br>            DB::commit();<br>        } catch (Exception $e) {<br>            DB::rollBack();<br>        }<br>    }</pre><p>Şimdi yaptığım şey bir controller sayfası oluşturup burada “save” fonksiyonu oluşturmak. İçersinde “try catch”, “DB” ve “Campaign” modelimi çağırıyorum. Bu kodumuzu çalıştırmak için index.php sayfasına gelecek her isteği karşılayacak bir yapımız olmalı. Basit bir routing oluşturalım.</p><pre>&lt;?php</pre><pre>namespace Route;</pre><pre>class Route<br>{<br>    public static function parseUrl()<br>    {<br>        $dirname = dirname($_SERVER[&#39;SCRIPT_NAME&#39;]);<br>        $dirname = $dirname != &#39;/&#39; ? $dirname : null;<br>        $basename = basename($_SERVER[&#39;SCRIPT_NAME&#39;]);<br>        $request_uri = str_replace([$dirname, $basename], &#39;&#39;, $_SERVER[&#39;REQUEST_URI&#39;]);<br>        return $request_uri;<br>    }</pre><pre>public static function run($url, $class, $methods = &#39;get&#39;)<br>    {<br>        $methods = explode(&#39;|&#39;, strtoupper($methods));<br>        if (in_array($_SERVER[&#39;REQUEST_METHOD&#39;], $methods)) {<br>            $request_uri = self::parseUrl();<br>            if (preg_match(&#39;@^&#39; . $url . &#39;$@&#39;, $request_uri, $parameters)) {<br>                $controllerFile =  &#39;app/&#39; . $class[0] . &#39;.php&#39;;<br>                if (file_exists(str_replace(&#39;\\&#39;, &#39;/&#39;, $controllerFile))) {<br>                    call_user_func_array([new $class[0](), $class[1]], []);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Basit olarak sınıfı , methodu ve url check ederek php “call_user_func_array” fonksiyonu ile çağırdığımız sınıf içersindeki fonksiyona erişebiliyoruz.</p><p>Son olarak “index.php” dosyamızda route yapıyoruz.</p><pre>&lt;?php</pre><pre>use App\Models\Database;<br>use Route\Route;</pre><pre>require &#39;vendor/autoload.php&#39;;<br>//Initialize<br>new Database();<br>Route::run(&#39;/campaign/save&#39;, [CampaignController::class, &#39;save&#39;], &#39;get&#39;);<br></pre><p>Final olarak çıktımıza erişmek için tarayıcımızda “<a href="http://127.0.0.1:14380/campaign/save">http://domain/campaign/save</a>” gittiğinizde save işlemini başarılı yapmış olacaksınız. Bendeki görselleri aşağıya ekliyor olacağım anca bendeki kod yapısı çok farklı olduğundan burada ekrana bir çıktı basmayacaktır. Olabildiğince sadeleştirip basit tutmaya çalıştım. Böyle yapmaya çalışırken namespacelerde hata olabilir. Kusuruma bakmayın. Umarım bir çok kişi için açıklayıcı olmuştur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*I1nt3GJD7s-GtVIh3rWJJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*d4wHqTo8UiBfxEhgeN8iyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wdXvN12PL0p2WMyHWqKiQw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1a63063527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain Of Responsibility Pattern Kullanımı]]></title>
            <link>https://medium.com/@celalsahinaltinisik/chain-of-responsibility-pattern-kullan%C4%B1m%C4%B1-4a1370a14c44?source=rss-b0527e80d405------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a1370a14c44</guid>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[pattern-kullanımı]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Celalsahinaltinisik]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 21:16:49 GMT</pubDate>
            <atom:updated>2022-10-23T21:16:49.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Uygulama yazarken kodun ileriye dönük, esnek, yönetilebilir ve karmaşalarının önüne geçmek için tasarım modellerine (design patterns) başvururuz.</p><p>Chain Of Responsibility uygulama geliştirirken kullanılabilirliği yüksek bir modeldir. Bu yapıya başvurmak için birden çok örnek oluşturulabilir.</p><p>Bir e-ticaret hizmetinde indirim veya puan hesaplaması her zaman istenilen bir özelliktir. Bir panel arayüz düşünelim. Bu arayüzden ürün ve kategoriler tanımlayarak kullanıcıların yaptığı alışverişlerde kazanacakları puanları tanımlıyoruz. Böyle bir özellik sürekli geliştirmeye açık olacağından farklı talepler gelecektir. Hesaplama işlemleri her zaman can sıkıcı ve hassas olduğundan kod karmaşası en son isteyeceğiniz şey olur.</p><p>Kullanıcı “x” ürünü satın alır ve bu ürüne tanımlı indirim vb. bir şey varsa “x” ürünü kurallar zincirinden geçerek işlenmesini (handle) sağlarız. Bir zincir düşünün her halkasında kurallarınız var. İlk halkadan son halkaya kadar sırası ile devam eder. Son halka da işlem bittiğinde verimizin son halini elde ederiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B10xDoP0OlDC7kyd" /><figcaption>Photo by <a href="https://unsplash.com/es/@kar111?utm_source=medium&amp;utm_medium=referral">Karine Avetisyan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Örnek; Kullanıcının sipariş ettiği ürünler üzerinden kazandığı puanları hesaplayacağız.</p><p>Kuralar;</p><ol><li>A ürünü için 10 puan</li><li>“Ay” kategorisi için 15 puan</li><li>“Mars” kategorisi ve J ürünü için 25 puan</li></ol><p>Kod karmaşasının önüne geçmek, kuralları gruplamak, ileriye dönük geliştirilebilir olmasını sağlamak. Kodunuzun kalitesini arttırmak ve tasarımınızı basit tutmak her zaman işinizi kolaylaştıracaktır.</p><p>İlk olarak “abstract” sınıfımızı tanımlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWuQ8NNpYJlIgTxEyf-8Jg.png" /></figure><pre>&lt;?php</pre><pre>namespace App\Abstracts;</pre><pre>use Illuminate\Database\Eloquent\Collection;</pre><pre>abstract class PointsCalculator<br>{<br>    protected $successor;<br>    private $collectData = [];</pre><pre>public abstract function calculator(Collection $collectionData);</pre><pre>public function setSuccessor(PointsCalculator $successor)<br>    {<br>        $this-&gt;successor = $successor;<br>    }</pre><pre>public function next(Collection $collectionData)<br>    {<br>        $this-&gt;collectData = $collectionData;<br>        if ($this-&gt;successor) {<br>            return $this-&gt;successor-&gt;calculator($collectionData);<br>        }<br>    }</pre><pre>public function getCollectData()<br>    {<br>        return $this-&gt;collectData;<br>    }<br>}</pre><p>Şimdi sınıflarımızı oluşturalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5lWtCjBd7aedwO1KdhIDg.png" /></figure><pre>&lt;?php</pre><pre>namespace App\Helpers;</pre><pre>use App\Abstracts\PointsCalculator;<br>use Exception;<br>use Illuminate\Database\Eloquent\Collection;</pre><pre>class BothPoints extends PointsCalculator<br>{<br>    const RULES = [<br>        &#39;POINTS&#39;    =&gt; 25,<br>        &#39;PRODUCT&#39;   =&gt; &#39;J&#39;,<br>        &#39;CATEGORY&#39;  =&gt; &#39;Mars&#39;<br>    ];</pre><pre>public function calculator(Collection $calculator)<br>    {<br>        try {<br>            if ($calculator-&gt;isNotEmpty()) {<br>                foreach ($calculator as $key =&gt; &amp;$order) {<br>                    if ($order-&gt;product == self::RULES[&#39;PRODUCT&#39;] &amp;&amp; $order-&gt;category == self::RULES[&#39;CATEGORY&#39;]) {<br>                        $order-&gt;totalPoints += self::RULES[&#39;POINTS&#39;];<br>                    }<br>                }<br>            }<br>        } catch (Exception $exception) {<br>            throw new Exception(&quot;Something is wrong&quot;);<br>        }<br>        return $this-&gt;next($calculator);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdU0Bu_ERTPAcrjNBCqffQ.png" /></figure><pre>&lt;?php</pre><pre>namespace App\Helpers;</pre><pre>use App\Abstracts\PointsCalculator;<br>use Exception;<br>use Illuminate\Database\Eloquent\Collection;</pre><pre>class CategoryPoints extends PointsCalculator<br>{<br>    const RULES = [<br>        &#39;POINTS&#39;    =&gt; 15,<br>        &#39;CATEGORY&#39;  =&gt; &#39;Ay&#39;<br>    ];<br>    public function calculator(Collection $calculator)<br>    {<br>        try {<br>            if ($calculator-&gt;isNotEmpty()) {<br>                foreach ($calculator as $key =&gt; &amp;$order) {<br>                    if ($order-&gt;category == self::RULES[&#39;CATEGORY&#39;]) {<br>                        $order-&gt;totalPoints += self::RULES[&#39;POINTS&#39;];<br>                    }<br>                }<br>            }<br>        } catch (Exception $exception) {<br>            throw new Exception(&quot;Something is wrong&quot;);<br>        }<br>        return $this-&gt;next($calculator);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76hBitJJv6Q4NPb8EyPXmA.png" /></figure><pre>&lt;?php</pre><pre>namespace App\Helpers;</pre><pre>use App\Abstracts\PointsCalculator;<br>use Exception;<br>use Illuminate\Database\Eloquent\Collection;</pre><pre>class ProductPoints extends PointsCalculator<br>{<br>    const RULES = [<br>        &#39;POINTS&#39;    =&gt; 10,<br>        &#39;PRODUCT&#39;  =&gt; &#39;A&#39;<br>    ];</pre><pre>public function calculator(Collection $calculator)<br>    {<br>        try {<br>            if ($calculator-&gt;isNotEmpty()) {<br>                foreach ($calculator as $key =&gt; &amp;$order) {<br>                    if ($order-&gt;product == self::RULES[&#39;PRODUCT&#39;]) {<br>                        $order-&gt;totalPoints += self::RULES[&#39;POINTS&#39;];<br>                    }<br>                }<br>            }<br>        } catch (Exception $exception) {<br>            throw new Exception(&quot;Something is wrong&quot;);<br>        }<br>        return $this-&gt;next($calculator);<br>    }<br>}</pre><p>Son olarak sınıflarımızı çağırarak verinin işlenmesini sağlayacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ue9HgXrWdh07bUCddVJrlw.png" /></figure><p>Burada dikkat edilmesi gereken nokta işlemlerin son zincir halkasına gelindiğinde bitmesini sağlamaktır. BothPoints sınıfını zincirin sonunda, kendi “calculator” fonksiyonunu çalıştırıp duracaktır. Aksi takdirde “BothPoints” sınıfınıda successor fonksiyonuna verirseniz hata alacaksınız.Burada bir sınıfınız dışarıda kalmalı.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKhllAfSfsh7NhFRJDYPqA.png" /></figure><p>Sonuç:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLi0ysBaljTj4nqqYrfC7g.png" /></figure><p>Ek olarak şunları söylemeliyim. Burada interface ile abstract sınıfımıza implement edilebilir. Kurallar bir tablodan çekilebilir ve if koşullarını daha dinamik(tablodan) yaparak kodun verimliliğini yükseltebilirsiniz.</p><p>Umarım faydalı olmuştur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a1370a14c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>